feat: spaces redesign, model selector, auth fixes

Spaces:
- Perplexity-like UI with collaboration features
- Space detail page with threads/members tabs
- Invite members via email, role management
- New space creation with icon/color picker

Model selector:
- Added Ollama client for free Auto model
- GooSeek 1.0 via Timeweb (tariff-based)
- Frontend model dropdown in ChatInput

Auth & Infrastructure:
- Fixed auth-svc missing from Dockerfile.all
- Removed duplicate ratelimit_tiered.go (conflict)
- Added Redis to api-gateway for rate limiting
- Fixed Next.js proxy for local development

UI improvements:
- Redesigned login button in sidebar (gradient)
- Settings page with tabs (account/billing/prefs)
- Auth pages visual refresh

Made-with: Cursor
This commit is contained in:
home
2026-02-28 02:30:05 +03:00
parent a0e3748dde
commit e6b9cfc60a
33 changed files with 2940 additions and 810 deletions

View File

@@ -1,144 +1,141 @@
# Недоделки — начать отсюда # Недоделки — начать отсюда
## Последнее исправление (28.02.2026)
### Fix: auth-svc не собирался в Docker
- Добавлена строка сборки `auth-svc` в `Dockerfile.all`
- Удалён дубликат `ratelimit_tiered.go` (конфликт типов с Redis-версией)
- Добавлен REDIS_URL в api-gateway для rate limiting
- Пересоздан тестовый пользователь через API
---
## Последнее изменение (28.02.2026) ## Последнее изменение (28.02.2026)
**Создан полный UI для авторизации:**
- Модальные окна login/register
- Страницы /login, /register, /forgot-password, /reset-password
- UserMenu в сайдбаре
- AuthContext для управления состоянием
## Сделано (полностью) **Обновлён дизайн страниц авторизации:**
### 1. Auth UI (NEW) ### Сделано (полностью)
**Новые файлы:** #### Страницы авторизации в стиле сайта
- `/login` — переделана с градиентным фоном, фирменным логотипом, анимациями
- `/register` — аналогично, единый стиль с login
- `/forgot-password`сброс пароля в новом дизайне
- `/reset-password` — установка нового пароля в новом дизайне
**API клиент:** Изменения:
- `backend/webui/src/lib/auth.ts` — функции для работы с auth API, хранение токенов - `bg-gradient-main` вместо простого `bg-base`
- Фирменный логотип GooSeek (font-black italic + иконка Sparkles)
- Gradient blur декорации на фоне
- Карточка с градиентной рамкой и backdrop-blur
- Анимации появления (framer-motion)
- Footer с копирайтом
**Контекст:** ---
- `backend/webui/src/lib/contexts/AuthContext.tsx` — React контекст для auth состояния
**Компоненты:** **Ранее: Spaces как у Perplexity + коллаборация:**
- `backend/webui/src/components/auth/AuthModal.tsx` — модальное окно
- `backend/webui/src/components/auth/LoginForm.tsx` — форма входа
- `backend/webui/src/components/auth/RegisterForm.tsx` — форма регистрации
- `backend/webui/src/components/auth/ForgotPasswordForm.tsx`сброс пароля
- `backend/webui/src/components/auth/UserMenu.tsx` — меню пользователя
- `backend/webui/src/components/auth/index.ts` — экспорты
**Страницы:** ### Сделано (полностью)
- `backend/webui/src/app/(auth)/login/page.tsx`
- `backend/webui/src/app/(auth)/register/page.tsx`
- `backend/webui/src/app/(auth)/forgot-password/page.tsx`
- `backend/webui/src/app/(auth)/reset-password/page.tsx`
- `backend/webui/src/app/(auth)/layout.tsx`
**Интеграция:** #### 1. Backend - Space Members
- `providers.tsx` — добавлен AuthProvider и AuthModal - Добавлена таблица `space_members` (space_id, user_id, role)
- `Sidebar.tsx` — кнопки входа/регистрации для гостей, профиль для авторизованных - Добавлена таблица `space_invites` (приглашения по токену)
- Методы: `GetMembers`, `AddMember`, `RemoveMember`, `IsMember`
- Методы: `CreateInvite`, `GetInviteByToken`, `DeleteInvite`
- Обновлён `GetByMemberID` - возвращает пространства где пользователь участник
**Функционал:** #### 2. Frontend - Types & API
- Модальные окна для быстрого входа без перехода на страницу - Добавлены типы: `SpaceMember`, `SpaceInvite`
- Отдельные страницы для полноценного входа - Обновлён тип `Space` с полями `members`, `memberCount`, `userId`
- Валидация паролей в реальном времени - API методы: `fetchSpaceMembers`, `inviteToSpace`, `removeSpaceMember`, `acceptSpaceInvite`, `fetchSpaceThreads`
- Показ/скрытие пароля
- Запоминание пользователя
- Сброс пароля по email
- Автоматический refresh токенов
- Отображение tier (Free/Pro/Business)
### 2. Auth Service (Backend) #### 3. Страница /spaces - Новый дизайн
- Карточки пространств с градиентным фоном
- Показывает: название, описание, кол-во участников, кол-во тредов
- Аватары участников на карточке
- Поиск по пространствам
- Требует авторизации
**Файлы:** #### 4. Страница /spaces/[id] - Детали пространства
- `backend/internal/auth/types.go` - Заголовок с названием и описанием
- `backend/internal/auth/repository.go` - Табы: Треды / Участники
- `backend/cmd/auth-svc/main.go` - Список тредов пространства с датами
- Список участников с ролями (owner/admin/member)
- Кнопка "Начать новый тред"
- Модалка приглашения участников по email
- Удаление участников (для admin/owner)
**Эндпоинты:** #### 5. Страница /spaces/new - Создание
| Method | Path | Описание | - Превью карточки в реальном времени
|--------|------|----------| - Выбор иконки (эмодзи)
| POST | `/api/v1/auth/register` | Регистрация | - Выбор цвета (6 вариантов)
| POST | `/api/v1/auth/login` | Вход | - Переключатель приватности
| POST | `/api/v1/auth/refresh` | Обновление токена | - AI инструкции для пространства
| POST | `/api/v1/auth/logout` | Выход |
| POST | `/api/v1/auth/logout-all` | Выход со всех устройств |
| GET | `/api/v1/auth/validate` | Валидация токена |
| GET | `/api/v1/auth/me` | Профиль |
| PUT | `/api/v1/auth/me` | Обновить профиль |
| POST | `/api/v1/auth/change-password` | Смена пароля |
| POST | `/api/v1/auth/forgot-password` | Запрос сброса |
| POST | `/api/v1/auth/reset-password` | Сброс пароля |
### 3. Ранее — Аудит безопасности #### 6. Ранее добавлено
- Селектор модели (Auto/GooSeek 1.0)
- Ollama клиент для бесплатной модели
- Обновлённая кнопка "Войти" в сайдбаре
- Репозитории с фильтрацией по user_id ### Файлы изменены/созданы
- JWT middleware во всех сервисах
- Tiered rate limiting (free/pro/business) ```
- Usage tracking backend/internal/db/
- LLM limits └── space_repo.go (UPDATED - members, invites)
backend/webui/src/
├── lib/
│ ├── types.ts (UPDATED - SpaceMember, SpaceInvite)
│ └── api.ts (UPDATED - space members API)
├── app/(main)/spaces/
│ ├── page.tsx (REWRITTEN - новый дизайн)
│ ├── new/page.tsx (REWRITTEN - с превью)
│ └── [id]/page.tsx (NEW - детали пространства)
└── components/
├── Sidebar.tsx (UPDATED - кнопка войти)
└── ChatInput.tsx (UPDATED - селектор модели)
backend/internal/llm/
├── ollama.go (NEW)
└── client.go (UPDATED)
backend/pkg/config/config.go (UPDATED - Ollama config)
backend/cmd/agent-svc/main.go (UPDATED - Ollama support)
```
## Осталось сделать ## Осталось сделать
### Высокий приоритет: ### Высокий приоритет:
1. **Проверить компиляцию**`cd backend && go build ./...` 1. **Backend API endpoints** — добавить API для:
2. **Протестировать auth flow** — регистрация → логин → refresh → logout - `GET /api/v1/spaces/:id/members`
3. **Добавить billing-svc** — интеграция с ЮKassa - `POST /api/v1/spaces/:id/invite`
- `DELETE /api/v1/spaces/:id/members/:userId`
- `POST /api/v1/spaces/invite/:token/accept`
- `GET /api/v1/spaces/:id/threads`
2. **Email отправка** — отправлять email с приглашением
3. **Ollama в docker-compose** — добавить сервис ollama
### Средний приоритет: ### Средний приоритет:
4. **OAuth провайдеры** — Google, GitHub, Yandex 4. **OAuth провайдеры** — Google, GitHub, Yandex
5. **Email уведомления** — подтверждение email, сброс пароля 5. **Подтверждение email** — отправка письма при регистрации
6. **Страница настроек профиля** — редактирование name, avatar 6. **Real-time обновления** — WebSocket для тредов в пространстве
7. **Страница подписки** — /settings/billing с выбором тарифа 7. **Уведомления** — когда кто-то добавляет сообщение в тред
### Низкий приоритет: ### Низкий приоритет:
8. **2FA** — TOTP аутентификация 8. **Интеграция оплаты** — ЮKassa для пополнения баланса
9. **Session management** — список активных сессий 9. **2FA** — TOTP аутентификация
10. **Account deletion** — удаление аккаунта 10. **Экспорт тредов** — PDF/Markdown
## Контекст ## Контекст
### Новые файлы UI: ### Модели:
``` | ID | Provider | Тариф |
backend/webui/src/ |----|----------|-------|
├── lib/ | auto | ollama | Бесплатно |
│ ├── auth.ts (NEW) | gooseek-1.0 | timeweb | По тарифу |
│ └── contexts/
│ └── AuthContext.tsx (NEW)
├── components/
│ └── auth/
│ ├── AuthModal.tsx (NEW)
│ ├── LoginForm.tsx (NEW)
│ ├── RegisterForm.tsx (NEW)
│ ├── ForgotPasswordForm.tsx (NEW)
│ ├── UserMenu.tsx (NEW)
│ └── index.ts (NEW)
└── app/
└── (auth)/
├── layout.tsx (NEW)
├── login/page.tsx (NEW)
├── register/page.tsx (NEW)
├── forgot-password/page.tsx (NEW)
└── reset-password/page.tsx (NEW)
```
### Обновлённые файлы: ### Роли в пространстве:
``` - `owner` — создатель, полные права
backend/webui/src/app/providers.tsx — AuthProvider + AuthModal - `admin` — может приглашать/удалять участников
backend/webui/src/components/Sidebar.tsx — кнопки auth + профиль - `member` — может создавать треды
```
### Хранение токенов:
```
localStorage:
- token: JWT access token
- refreshToken: refresh token
- user: JSON с данными пользователя
```
### Auth flow:
1. Гость видит кнопки "Войти" / "Регистрация" в сайдбаре
2. Клик открывает модальное окно (или переход на страницу)
3. После успешного входа — сохранение токенов, обновление UI
4. При истечении access token — автоматический refresh
5. При logout — очистка localStorage

View File

@@ -93,15 +93,23 @@ func main() {
providerID = "timeweb" providerID = "timeweb"
modelKey = "gpt-4o" modelKey = "gpt-4o"
} else if providerID == "" { } else if providerID == "" {
providerID = "openai" providerID = "ollama"
modelKey = "gpt-4o-mini" modelKey = cfg.OllamaModelKey
}
baseURL := cfg.TimewebAPIBaseURL
if providerID == "ollama" {
baseURL = cfg.OllamaBaseURL
if modelKey == "" {
modelKey = cfg.OllamaModelKey
}
} }
llmClient, err := llm.NewClient(llm.ProviderConfig{ llmClient, err := llm.NewClient(llm.ProviderConfig{
ProviderID: providerID, ProviderID: providerID,
ModelKey: modelKey, ModelKey: modelKey,
APIKey: getAPIKey(cfg, providerID), APIKey: getAPIKey(cfg, providerID),
BaseURL: cfg.TimewebAPIBaseURL, BaseURL: baseURL,
AgentAccessID: cfg.TimewebAgentAccessID, AgentAccessID: cfg.TimewebAgentAccessID,
}) })
if err != nil { if err != nil {
@@ -200,6 +208,8 @@ func main() {
func getAPIKey(cfg *config.Config, providerID string) string { func getAPIKey(cfg *config.Config, providerID string) string {
switch providerID { switch providerID {
case "ollama":
return ""
case "timeweb": case "timeweb":
return cfg.TimewebAPIKey return cfg.TimewebAPIKey
case "openai": case "openai":

View File

@@ -2,6 +2,7 @@ package main
import ( import (
"bufio" "bufio"
"context"
"fmt" "fmt"
"io" "io"
"log" "log"
@@ -15,6 +16,7 @@ import (
"github.com/gofiber/fiber/v2/middleware/logger" "github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gooseek/backend/pkg/config" "github.com/gooseek/backend/pkg/config"
"github.com/gooseek/backend/pkg/middleware" "github.com/gooseek/backend/pkg/middleware"
"github.com/redis/go-redis/v9"
) )
var svcURLs map[string]string var svcURLs map[string]string
@@ -25,6 +27,19 @@ func main() {
log.Fatal("Failed to load config:", err) log.Fatal("Failed to load config:", err)
} }
opt, err := redis.ParseURL(cfg.RedisURL)
if err != nil {
log.Printf("Warning: failed to parse Redis URL, rate limiting will be disabled: %v", err)
}
var redisClient *redis.Client
if opt != nil {
redisClient = redis.NewClient(opt)
if _, err := redisClient.Ping(context.Background()).Result(); err != nil {
log.Printf("Warning: Redis not available, rate limiting will be disabled: %v", err)
redisClient = nil
}
}
svcURLs = map[string]string{ svcURLs = map[string]string{
"auth": cfg.AuthSvcURL, "auth": cfg.AuthSvcURL,
"chat": cfg.ChatSvcURL, "chat": cfg.ChatSvcURL,
@@ -62,7 +77,9 @@ func main() {
AllowGuest: true, AllowGuest: true,
})) }))
if redisClient != nil {
app.Use(middleware.TieredRateLimit(middleware.TieredRateLimitConfig{ app.Use(middleware.TieredRateLimit(middleware.TieredRateLimitConfig{
RedisClient: redisClient,
Tiers: map[string]middleware.TierConfig{ Tiers: map[string]middleware.TierConfig{
"free": {Max: 60, Window: time.Minute}, "free": {Max: 60, Window: time.Minute},
"pro": {Max: 300, Window: time.Minute}, "pro": {Max: 300, Window: time.Minute},
@@ -70,6 +87,7 @@ func main() {
}, },
DefaultTier: "free", DefaultTier: "free",
})) }))
}
app.Get("/health", func(c *fiber.Ctx) error { app.Get("/health", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{"status": "ok"}) return c.JSON(fiber.Map{"status": "ok"})

View File

@@ -12,6 +12,7 @@ COPY . .
# Build all services # Build all services
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /bin/api-gateway ./cmd/api-gateway RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /bin/api-gateway ./cmd/api-gateway
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /bin/auth-svc ./cmd/auth-svc
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /bin/agent-svc ./cmd/agent-svc RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /bin/agent-svc ./cmd/agent-svc
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /bin/chat-svc ./cmd/chat-svc RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /bin/chat-svc ./cmd/chat-svc
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /bin/search-svc ./cmd/search-svc RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /bin/search-svc ./cmd/search-svc

View File

@@ -41,6 +41,7 @@ services:
- LEARNING_SVC_URL=http://learning-svc:3034 - LEARNING_SVC_URL=http://learning-svc:3034
- ADMIN_SVC_URL=http://admin-svc:3040 - ADMIN_SVC_URL=http://admin-svc:3040
- JWT_SECRET=${JWT_SECRET} - JWT_SECRET=${JWT_SECRET}
- REDIS_URL=redis://redis:6379
ports: ports:
- "3015:3015" - "3015:3015"
depends_on: depends_on:
@@ -49,6 +50,7 @@ services:
- agent-svc - agent-svc
- thread-svc - thread-svc
- admin-svc - admin-svc
- redis
networks: networks:
- gooseek - gooseek

View File

@@ -38,6 +38,7 @@ func (r *Repository) RunMigrations(ctx context.Context) error {
avatar TEXT, avatar TEXT,
role VARCHAR(50) DEFAULT 'user', role VARCHAR(50) DEFAULT 'user',
tier VARCHAR(50) DEFAULT 'free', tier VARCHAR(50) DEFAULT 'free',
balance DECIMAL(12,2) DEFAULT 0,
email_verified BOOLEAN DEFAULT FALSE, email_verified BOOLEAN DEFAULT FALSE,
provider VARCHAR(50) DEFAULT 'local', provider VARCHAR(50) DEFAULT 'local',
provider_id VARCHAR(255), provider_id VARCHAR(255),
@@ -69,6 +70,8 @@ func (r *Repository) RunMigrations(ctx context.Context) error {
created_at TIMESTAMPTZ DEFAULT NOW() created_at TIMESTAMPTZ DEFAULT NOW()
)`, )`,
`CREATE INDEX IF NOT EXISTS idx_password_reset_tokens ON password_reset_tokens(token)`, `CREATE INDEX IF NOT EXISTS idx_password_reset_tokens ON password_reset_tokens(token)`,
`ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS balance DECIMAL(12,2) DEFAULT 0`,
} }
for _, m := range migrations { for _, m := range migrations {
@@ -125,18 +128,19 @@ func (r *Repository) CreateUser(ctx context.Context, email, password, name strin
func (r *Repository) GetUserByEmail(ctx context.Context, email string) (*User, error) { func (r *Repository) GetUserByEmail(ctx context.Context, email string) (*User, error) {
query := ` query := `
SELECT id, email, password_hash, name, avatar, role, tier, email_verified, SELECT id, email, password_hash, name, avatar, role, tier, balance, email_verified,
provider, provider_id, last_login_at, created_at, updated_at provider, provider_id, last_login_at, created_at, updated_at
FROM auth_users WHERE email = $1 FROM auth_users WHERE email = $1
` `
user := &User{} user := &User{}
var lastLogin, avatar, providerID sql.NullString var avatar, providerID sql.NullString
var lastLoginTime sql.NullTime var lastLoginTime sql.NullTime
var balance sql.NullFloat64
err := r.db.QueryRowContext(ctx, query, email).Scan( err := r.db.QueryRowContext(ctx, query, email).Scan(
&user.ID, &user.Email, &user.PasswordHash, &user.Name, &avatar, &user.ID, &user.Email, &user.PasswordHash, &user.Name, &avatar,
&user.Role, &user.Tier, &user.EmailVerified, &user.Provider, &user.Role, &user.Tier, &balance, &user.EmailVerified, &user.Provider,
&providerID, &lastLoginTime, &user.CreatedAt, &user.UpdatedAt, &providerID, &lastLoginTime, &user.CreatedAt, &user.UpdatedAt,
) )
@@ -156,14 +160,16 @@ func (r *Repository) GetUserByEmail(ctx context.Context, email string) (*User, e
if lastLoginTime.Valid { if lastLoginTime.Valid {
user.LastLoginAt = lastLoginTime.Time user.LastLoginAt = lastLoginTime.Time
} }
_ = lastLogin if balance.Valid {
user.Balance = balance.Float64
}
return user, nil return user, nil
} }
func (r *Repository) GetUserByID(ctx context.Context, id string) (*User, error) { func (r *Repository) GetUserByID(ctx context.Context, id string) (*User, error) {
query := ` query := `
SELECT id, email, password_hash, name, avatar, role, tier, email_verified, SELECT id, email, password_hash, name, avatar, role, tier, balance, email_verified,
provider, provider_id, last_login_at, created_at, updated_at provider, provider_id, last_login_at, created_at, updated_at
FROM auth_users WHERE id = $1 FROM auth_users WHERE id = $1
` `
@@ -171,10 +177,11 @@ func (r *Repository) GetUserByID(ctx context.Context, id string) (*User, error)
user := &User{} user := &User{}
var avatar, providerID sql.NullString var avatar, providerID sql.NullString
var lastLoginTime sql.NullTime var lastLoginTime sql.NullTime
var balance sql.NullFloat64
err := r.db.QueryRowContext(ctx, query, id).Scan( err := r.db.QueryRowContext(ctx, query, id).Scan(
&user.ID, &user.Email, &user.PasswordHash, &user.Name, &avatar, &user.ID, &user.Email, &user.PasswordHash, &user.Name, &avatar,
&user.Role, &user.Tier, &user.EmailVerified, &user.Provider, &user.Role, &user.Tier, &balance, &user.EmailVerified, &user.Provider,
&providerID, &lastLoginTime, &user.CreatedAt, &user.UpdatedAt, &providerID, &lastLoginTime, &user.CreatedAt, &user.UpdatedAt,
) )
@@ -194,6 +201,9 @@ func (r *Repository) GetUserByID(ctx context.Context, id string) (*User, error)
if lastLoginTime.Valid { if lastLoginTime.Valid {
user.LastLoginAt = lastLoginTime.Time user.LastLoginAt = lastLoginTime.Time
} }
if balance.Valid {
user.Balance = balance.Float64
}
return user, nil return user, nil
} }
@@ -254,6 +264,22 @@ func (r *Repository) UpdateRole(ctx context.Context, userID string, role UserRol
return err return err
} }
func (r *Repository) UpdateBalance(ctx context.Context, userID string, amount float64) error {
_, err := r.db.ExecContext(ctx,
"UPDATE auth_users SET balance = balance + $2, updated_at = NOW() WHERE id = $1",
userID, amount,
)
return err
}
func (r *Repository) SetBalance(ctx context.Context, userID string, balance float64) error {
_, err := r.db.ExecContext(ctx,
"UPDATE auth_users SET balance = $2, updated_at = NOW() WHERE id = $1",
userID, balance,
)
return err
}
func (r *Repository) CreateRefreshToken(ctx context.Context, userID, userAgent, ip string, duration time.Duration) (*RefreshToken, error) { func (r *Repository) CreateRefreshToken(ctx context.Context, userID, userAgent, ip string, duration time.Duration) (*RefreshToken, error) {
token := generateSecureToken(32) token := generateSecureToken(32)

View File

@@ -12,6 +12,7 @@ type User struct {
Avatar string `json:"avatar,omitempty"` Avatar string `json:"avatar,omitempty"`
Role string `json:"role"` Role string `json:"role"`
Tier string `json:"tier"` Tier string `json:"tier"`
Balance float64 `json:"balance"`
EmailVerified bool `json:"emailVerified"` EmailVerified bool `json:"emailVerified"`
Provider string `json:"provider"` Provider string `json:"provider"`
ProviderID string `json:"providerId,omitempty"` ProviderID string `json:"providerId,omitempty"`

View File

@@ -22,6 +22,30 @@ type Space struct {
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"` UpdatedAt time.Time `json:"updatedAt"`
ThreadCount int `json:"threadCount,omitempty"` ThreadCount int `json:"threadCount,omitempty"`
Members []*SpaceMember `json:"members,omitempty"`
MemberCount int `json:"memberCount,omitempty"`
}
type SpaceMember struct {
ID string `json:"id"`
SpaceID string `json:"spaceId"`
UserID string `json:"userId"`
Role string `json:"role"`
Email string `json:"email,omitempty"`
Name string `json:"name,omitempty"`
Avatar string `json:"avatar,omitempty"`
JoinedAt time.Time `json:"joinedAt"`
}
type SpaceInvite struct {
ID string `json:"id"`
SpaceID string `json:"spaceId"`
Email string `json:"email"`
Role string `json:"role"`
InvitedBy string `json:"invitedBy"`
Token string `json:"token"`
ExpiresAt time.Time `json:"expiresAt"`
CreatedAt time.Time `json:"createdAt"`
} }
type SpaceRepository struct { type SpaceRepository struct {
@@ -50,6 +74,28 @@ func (r *SpaceRepository) RunMigrations(ctx context.Context) error {
updated_at TIMESTAMPTZ DEFAULT NOW() updated_at TIMESTAMPTZ DEFAULT NOW()
)`, )`,
`CREATE INDEX IF NOT EXISTS idx_spaces_user ON spaces(user_id)`, `CREATE INDEX IF NOT EXISTS idx_spaces_user ON spaces(user_id)`,
`CREATE TABLE IF NOT EXISTS space_members (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
space_id UUID NOT NULL REFERENCES spaces(id) ON DELETE CASCADE,
user_id UUID NOT NULL,
role VARCHAR(20) DEFAULT 'member',
joined_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(space_id, user_id)
)`,
`CREATE INDEX IF NOT EXISTS idx_space_members_space ON space_members(space_id)`,
`CREATE INDEX IF NOT EXISTS idx_space_members_user ON space_members(user_id)`,
`CREATE TABLE IF NOT EXISTS space_invites (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
space_id UUID NOT NULL REFERENCES spaces(id) ON DELETE CASCADE,
email VARCHAR(255) NOT NULL,
role VARCHAR(20) DEFAULT 'member',
invited_by UUID NOT NULL,
token VARCHAR(64) NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
)`,
`CREATE INDEX IF NOT EXISTS idx_space_invites_token ON space_invites(token)`,
`CREATE INDEX IF NOT EXISTS idx_space_invites_email ON space_invites(email)`,
} }
for _, m := range migrations { for _, m := range migrations {
@@ -175,3 +221,176 @@ func (r *SpaceRepository) Delete(ctx context.Context, id, userID string) error {
} }
return nil return nil
} }
func (r *SpaceRepository) GetMembers(ctx context.Context, spaceID string) ([]*SpaceMember, error) {
query := `
SELECT sm.id, sm.space_id, sm.user_id, sm.role, sm.joined_at,
COALESCE(u.email, '') as email,
COALESCE(u.name, '') as name,
COALESCE(u.avatar, '') as avatar
FROM space_members sm
LEFT JOIN auth_users u ON sm.user_id = u.id
WHERE sm.space_id = $1
ORDER BY sm.joined_at ASC
`
rows, err := r.db.db.QueryContext(ctx, query, spaceID)
if err != nil {
return nil, err
}
defer rows.Close()
var members []*SpaceMember
for rows.Next() {
var m SpaceMember
if err := rows.Scan(&m.ID, &m.SpaceID, &m.UserID, &m.Role, &m.JoinedAt, &m.Email, &m.Name, &m.Avatar); err != nil {
return nil, err
}
members = append(members, &m)
}
return members, nil
}
func (r *SpaceRepository) AddMember(ctx context.Context, spaceID, userID, role string) error {
query := `
INSERT INTO space_members (space_id, user_id, role)
VALUES ($1, $2, $3)
ON CONFLICT (space_id, user_id) DO NOTHING
`
_, err := r.db.db.ExecContext(ctx, query, spaceID, userID, role)
return err
}
func (r *SpaceRepository) RemoveMember(ctx context.Context, spaceID, userID string) error {
result, err := r.db.db.ExecContext(ctx, "DELETE FROM space_members WHERE space_id = $1 AND user_id = $2", spaceID, userID)
if err != nil {
return err
}
rows, _ := result.RowsAffected()
if rows == 0 {
return ErrNotFound
}
return nil
}
func (r *SpaceRepository) UpdateMemberRole(ctx context.Context, spaceID, userID, role string) error {
result, err := r.db.db.ExecContext(ctx, "UPDATE space_members SET role = $3 WHERE space_id = $1 AND user_id = $2", spaceID, userID, role)
if err != nil {
return err
}
rows, _ := result.RowsAffected()
if rows == 0 {
return ErrNotFound
}
return nil
}
func (r *SpaceRepository) IsMember(ctx context.Context, spaceID, userID string) (bool, string, error) {
var role string
err := r.db.db.QueryRowContext(ctx, "SELECT role FROM space_members WHERE space_id = $1 AND user_id = $2", spaceID, userID).Scan(&role)
if err == sql.ErrNoRows {
return false, "", nil
}
if err != nil {
return false, "", err
}
return true, role, nil
}
func (r *SpaceRepository) GetByMemberID(ctx context.Context, userID string) ([]*Space, error) {
query := `
SELECT DISTINCT s.id, s.user_id, s.name, s.description, s.icon, s.color,
s.custom_instructions, s.default_focus_mode, s.default_model,
s.is_public, s.settings, s.created_at, s.updated_at,
(SELECT COUNT(*) FROM threads WHERE space_id = s.id) as thread_count,
(SELECT COUNT(*) FROM space_members WHERE space_id = s.id) as member_count
FROM spaces s
LEFT JOIN space_members sm ON s.id = sm.space_id
WHERE s.user_id = $1 OR sm.user_id = $1
ORDER BY s.updated_at DESC
`
rows, err := r.db.db.QueryContext(ctx, query, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var spaces []*Space
for rows.Next() {
var s Space
var settingsJSON []byte
if err := rows.Scan(
&s.ID, &s.UserID, &s.Name, &s.Description, &s.Icon, &s.Color,
&s.CustomInstructions, &s.DefaultFocusMode, &s.DefaultModel,
&s.IsPublic, &settingsJSON, &s.CreatedAt, &s.UpdatedAt, &s.ThreadCount, &s.MemberCount,
); err != nil {
return nil, err
}
json.Unmarshal(settingsJSON, &s.Settings)
spaces = append(spaces, &s)
}
return spaces, nil
}
func (r *SpaceRepository) CreateInvite(ctx context.Context, invite *SpaceInvite) error {
query := `
INSERT INTO space_invites (space_id, email, role, invited_by, token, expires_at)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, created_at
`
return r.db.db.QueryRowContext(ctx, query,
invite.SpaceID, invite.Email, invite.Role, invite.InvitedBy, invite.Token, invite.ExpiresAt,
).Scan(&invite.ID, &invite.CreatedAt)
}
func (r *SpaceRepository) GetInviteByToken(ctx context.Context, token string) (*SpaceInvite, error) {
query := `
SELECT id, space_id, email, role, invited_by, token, expires_at, created_at
FROM space_invites
WHERE token = $1 AND expires_at > NOW()
`
var inv SpaceInvite
err := r.db.db.QueryRowContext(ctx, query, token).Scan(
&inv.ID, &inv.SpaceID, &inv.Email, &inv.Role, &inv.InvitedBy, &inv.Token, &inv.ExpiresAt, &inv.CreatedAt,
)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
return &inv, nil
}
func (r *SpaceRepository) DeleteInvite(ctx context.Context, id string) error {
_, err := r.db.db.ExecContext(ctx, "DELETE FROM space_invites WHERE id = $1", id)
return err
}
func (r *SpaceRepository) GetInvitesBySpace(ctx context.Context, spaceID string) ([]*SpaceInvite, error) {
query := `
SELECT id, space_id, email, role, invited_by, token, expires_at, created_at
FROM space_invites
WHERE space_id = $1 AND expires_at > NOW()
ORDER BY created_at DESC
`
rows, err := r.db.db.QueryContext(ctx, query, spaceID)
if err != nil {
return nil, err
}
defer rows.Close()
var invites []*SpaceInvite
for rows.Next() {
var inv SpaceInvite
if err := rows.Scan(&inv.ID, &inv.SpaceID, &inv.Email, &inv.Role, &inv.InvitedBy, &inv.Token, &inv.ExpiresAt, &inv.CreatedAt); err != nil {
return nil, err
}
invites = append(invites, &inv)
}
return invites, nil
}

View File

@@ -79,6 +79,11 @@ type ProviderConfig struct {
func NewClient(cfg ProviderConfig) (Client, error) { func NewClient(cfg ProviderConfig) (Client, error) {
switch cfg.ProviderID { switch cfg.ProviderID {
case "ollama":
return NewOllamaClient(OllamaConfig{
BaseURL: cfg.BaseURL,
ModelKey: cfg.ModelKey,
})
case "timeweb": case "timeweb":
return NewTimewebClient(TimewebConfig{ return NewTimewebClient(TimewebConfig{
BaseURL: cfg.BaseURL, BaseURL: cfg.BaseURL,

View File

@@ -0,0 +1,233 @@
package llm
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
)
type OllamaClient struct {
baseClient
httpClient *http.Client
baseURL string
}
type OllamaConfig struct {
BaseURL string
ModelKey string
}
func NewOllamaClient(cfg OllamaConfig) (*OllamaClient, error) {
baseURL := cfg.BaseURL
if baseURL == "" {
baseURL = "http://ollama:11434"
}
modelKey := cfg.ModelKey
if modelKey == "" {
modelKey = "llama3.2"
}
return &OllamaClient{
baseClient: baseClient{
providerID: "ollama",
modelKey: modelKey,
},
httpClient: &http.Client{
Timeout: 300 * time.Second,
},
baseURL: baseURL,
}, nil
}
type ollamaChatRequest struct {
Model string `json:"model"`
Messages []ollamaMessage `json:"messages"`
Stream bool `json:"stream"`
Options *ollamaOptions `json:"options,omitempty"`
}
type ollamaMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type ollamaOptions struct {
Temperature float64 `json:"temperature,omitempty"`
NumPredict int `json:"num_predict,omitempty"`
TopP float64 `json:"top_p,omitempty"`
Stop []string `json:"stop,omitempty"`
}
type ollamaChatResponse struct {
Model string `json:"model"`
CreatedAt string `json:"created_at"`
Message ollamaMessage `json:"message"`
Done bool `json:"done"`
}
func (c *OllamaClient) StreamText(ctx context.Context, req StreamRequest) (<-chan StreamChunk, error) {
messages := make([]ollamaMessage, 0, len(req.Messages))
for _, m := range req.Messages {
messages = append(messages, ollamaMessage{
Role: string(m.Role),
Content: m.Content,
})
}
chatReq := ollamaChatRequest{
Model: c.modelKey,
Messages: messages,
Stream: true,
}
if req.Options.MaxTokens > 0 || req.Options.Temperature > 0 || req.Options.TopP > 0 || len(req.Options.StopWords) > 0 {
chatReq.Options = &ollamaOptions{}
if req.Options.MaxTokens > 0 {
chatReq.Options.NumPredict = req.Options.MaxTokens
}
if req.Options.Temperature > 0 {
chatReq.Options.Temperature = req.Options.Temperature
}
if req.Options.TopP > 0 {
chatReq.Options.TopP = req.Options.TopP
}
if len(req.Options.StopWords) > 0 {
chatReq.Options.Stop = req.Options.StopWords
}
}
body, err := json.Marshal(chatReq)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
url := fmt.Sprintf("%s/api/chat", c.baseURL)
httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
if resp.StatusCode != http.StatusOK {
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("Ollama API error: status %d, body: %s", resp.StatusCode, string(body))
}
ch := make(chan StreamChunk, 100)
go func() {
defer close(ch)
defer resp.Body.Close()
reader := bufio.NewReader(resp.Body)
for {
line, err := reader.ReadString('\n')
if err != nil {
if err != io.EOF {
return
}
return
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
var streamResp ollamaChatResponse
if err := json.Unmarshal([]byte(line), &streamResp); err != nil {
continue
}
if streamResp.Message.Content != "" {
ch <- StreamChunk{ContentChunk: streamResp.Message.Content}
}
if streamResp.Done {
ch <- StreamChunk{FinishReason: "stop"}
return
}
}
}()
return ch, nil
}
func (c *OllamaClient) GenerateText(ctx context.Context, req StreamRequest) (string, error) {
messages := make([]ollamaMessage, 0, len(req.Messages))
for _, m := range req.Messages {
messages = append(messages, ollamaMessage{
Role: string(m.Role),
Content: m.Content,
})
}
chatReq := ollamaChatRequest{
Model: c.modelKey,
Messages: messages,
Stream: false,
}
if req.Options.MaxTokens > 0 || req.Options.Temperature > 0 || req.Options.TopP > 0 {
chatReq.Options = &ollamaOptions{}
if req.Options.MaxTokens > 0 {
chatReq.Options.NumPredict = req.Options.MaxTokens
}
if req.Options.Temperature > 0 {
chatReq.Options.Temperature = req.Options.Temperature
}
if req.Options.TopP > 0 {
chatReq.Options.TopP = req.Options.TopP
}
}
body, err := json.Marshal(chatReq)
if err != nil {
return "", fmt.Errorf("failed to marshal request: %w", err)
}
url := fmt.Sprintf("%s/api/chat", c.baseURL)
httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
if err != nil {
return "", fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(httpReq)
if err != nil {
return "", fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return "", fmt.Errorf("Ollama API error: status %d, body: %s", resp.StatusCode, string(body))
}
var chatResp ollamaChatResponse
if err := json.NewDecoder(resp.Body).Decode(&chatResp); err != nil {
return "", fmt.Errorf("failed to decode response: %w", err)
}
if chatResp.Message.Content == "" {
return "", errors.New("empty response from Ollama")
}
return chatResp.Message.Content, nil
}

View File

@@ -70,6 +70,10 @@ type Config struct {
TimewebAPIKey string TimewebAPIKey string
TimewebProxySource string TimewebProxySource string
// Ollama (local LLM)
OllamaBaseURL string
OllamaModelKey string
// Timeouts // Timeouts
HTTPTimeout time.Duration HTTPTimeout time.Duration
LLMTimeout time.Duration LLMTimeout time.Duration
@@ -141,6 +145,9 @@ func Load() (*Config, error) {
TimewebAPIKey: getEnv("TIMEWEB_API_KEY", ""), TimewebAPIKey: getEnv("TIMEWEB_API_KEY", ""),
TimewebProxySource: getEnv("TIMEWEB_X_PROXY_SOURCE", "gooseek"), TimewebProxySource: getEnv("TIMEWEB_X_PROXY_SOURCE", "gooseek"),
OllamaBaseURL: getEnv("OLLAMA_BASE_URL", "http://ollama:11434"),
OllamaModelKey: getEnv("OLLAMA_MODEL", "llama3.2"),
HTTPTimeout: time.Duration(getEnvInt("HTTP_TIMEOUT_MS", 60000)) * time.Millisecond, HTTPTimeout: time.Duration(getEnvInt("HTTP_TIMEOUT_MS", 60000)) * time.Millisecond,
LLMTimeout: time.Duration(getEnvInt("LLM_TIMEOUT_MS", 120000)) * time.Millisecond, LLMTimeout: time.Duration(getEnvInt("LLM_TIMEOUT_MS", 120000)) * time.Millisecond,
ScrapeTimeout: time.Duration(getEnvInt("SCRAPE_TIMEOUT_MS", 25000)) * time.Millisecond, ScrapeTimeout: time.Duration(getEnvInt("SCRAPE_TIMEOUT_MS", 25000)) * time.Millisecond,

View File

@@ -144,6 +144,7 @@ type TieredRateLimitConfig struct {
RedisClient *redis.Client RedisClient *redis.Client
KeyPrefix string KeyPrefix string
Tiers map[string]TierConfig Tiers map[string]TierConfig
DefaultTier string
GetTierFunc func(*fiber.Ctx) string GetTierFunc func(*fiber.Ctx) string
KeyFunc func(*fiber.Ctx) string KeyFunc func(*fiber.Ctx) string
} }
@@ -157,16 +158,31 @@ func TieredRateLimit(cfg TieredRateLimitConfig) fiber.Handler {
if cfg.KeyPrefix == "" { if cfg.KeyPrefix == "" {
cfg.KeyPrefix = "ratelimit:tiered" cfg.KeyPrefix = "ratelimit:tiered"
} }
if cfg.DefaultTier == "" {
cfg.DefaultTier = "free"
}
if cfg.GetTierFunc == nil { if cfg.GetTierFunc == nil {
cfg.GetTierFunc = func(c *fiber.Ctx) string { return "default" } cfg.GetTierFunc = func(c *fiber.Ctx) string {
tier := GetUserTier(c)
if tier == "" {
return cfg.DefaultTier
}
return tier
}
} }
if cfg.KeyFunc == nil { if cfg.KeyFunc == nil {
cfg.KeyFunc = func(c *fiber.Ctx) string { return c.IP() } cfg.KeyFunc = func(c *fiber.Ctx) string {
userID := GetUserID(c)
if userID != "" {
return "user:" + userID
}
return "ip:" + c.IP()
}
} }
defaultTier := TierConfig{Max: 60, Window: time.Minute} defaultTierCfg := TierConfig{Max: 60, Window: time.Minute}
if _, ok := cfg.Tiers["default"]; !ok { if _, ok := cfg.Tiers[cfg.DefaultTier]; !ok {
cfg.Tiers["default"] = defaultTier cfg.Tiers[cfg.DefaultTier] = defaultTierCfg
} }
return func(c *fiber.Ctx) error { return func(c *fiber.Ctx) error {
@@ -174,7 +190,7 @@ func TieredRateLimit(cfg TieredRateLimitConfig) fiber.Handler {
tier := cfg.GetTierFunc(c) tier := cfg.GetTierFunc(c)
tierCfg, ok := cfg.Tiers[tier] tierCfg, ok := cfg.Tiers[tier]
if !ok { if !ok {
tierCfg = cfg.Tiers["default"] tierCfg = cfg.Tiers[cfg.DefaultTier]
} }
key := fmt.Sprintf("%s:%s:%s", cfg.KeyPrefix, tier, cfg.KeyFunc(c)) key := fmt.Sprintf("%s:%s:%s", cfg.KeyPrefix, tier, cfg.KeyFunc(c))

View File

@@ -1,158 +0,0 @@
package middleware
import (
"sync"
"time"
"github.com/gofiber/fiber/v2"
)
type TierConfig struct {
Max int
Window time.Duration
}
type TieredRateLimitConfig struct {
Tiers map[string]TierConfig
DefaultTier string
KeyFunc func(*fiber.Ctx) string
GetTierFunc func(*fiber.Ctx) string
}
type tieredRateLimiter struct {
requests map[string][]time.Time
mu sync.RWMutex
tiers map[string]TierConfig
}
func newTieredRateLimiter(tiers map[string]TierConfig) *tieredRateLimiter {
rl := &tieredRateLimiter{
requests: make(map[string][]time.Time),
tiers: tiers,
}
go rl.cleanup()
return rl
}
func (rl *tieredRateLimiter) cleanup() {
ticker := time.NewTicker(time.Minute)
for range ticker.C {
rl.mu.Lock()
now := time.Now()
for key, times := range rl.requests {
var valid []time.Time
for _, t := range times {
if now.Sub(t) < 5*time.Minute {
valid = append(valid, t)
}
}
if len(valid) == 0 {
delete(rl.requests, key)
} else {
rl.requests[key] = valid
}
}
rl.mu.Unlock()
}
}
func (rl *tieredRateLimiter) allow(key string, tier string) (bool, int, int) {
rl.mu.Lock()
defer rl.mu.Unlock()
cfg, ok := rl.tiers[tier]
if !ok {
cfg = rl.tiers["free"]
}
now := time.Now()
windowStart := now.Add(-cfg.Window)
times := rl.requests[key]
var valid []time.Time
for _, t := range times {
if t.After(windowStart) {
valid = append(valid, t)
}
}
remaining := cfg.Max - len(valid)
if remaining <= 0 {
rl.requests[key] = valid
return false, 0, cfg.Max
}
rl.requests[key] = append(valid, now)
return true, remaining - 1, cfg.Max
}
func TieredRateLimit(config TieredRateLimitConfig) fiber.Handler {
if config.Tiers == nil {
config.Tiers = map[string]TierConfig{
"free": {Max: 60, Window: time.Minute},
"pro": {Max: 300, Window: time.Minute},
"business": {Max: 1000, Window: time.Minute},
}
}
if config.DefaultTier == "" {
config.DefaultTier = "free"
}
if config.KeyFunc == nil {
config.KeyFunc = func(c *fiber.Ctx) string {
userID := GetUserID(c)
if userID != "" {
return "user:" + userID
}
return "ip:" + c.IP()
}
}
if config.GetTierFunc == nil {
config.GetTierFunc = func(c *fiber.Ctx) string {
tier := GetUserTier(c)
if tier == "" {
return config.DefaultTier
}
return tier
}
}
limiter := newTieredRateLimiter(config.Tiers)
return func(c *fiber.Ctx) error {
key := config.KeyFunc(c)
tier := config.GetTierFunc(c)
allowed, remaining, limit := limiter.allow(key, tier)
c.Set("X-RateLimit-Limit", formatInt(limit))
c.Set("X-RateLimit-Remaining", formatInt(remaining))
c.Set("X-RateLimit-Tier", tier)
if !allowed {
c.Set("Retry-After", "60")
return c.Status(429).JSON(fiber.Map{
"error": "Rate limit exceeded",
"tier": tier,
"limit": limit,
"retryAfter": 60,
})
}
return c.Next()
}
}
func formatInt(n int) string {
if n < 0 {
n = 0
}
s := ""
if n == 0 {
return "0"
}
for n > 0 {
s = string(rune('0'+n%10)) + s
n /= 10
}
return s
}

View File

@@ -3,13 +3,14 @@ const nextConfig = {
output: 'standalone', output: 'standalone',
reactStrictMode: true, reactStrictMode: true,
env: { env: {
API_URL: process.env.API_URL || 'http://api-gateway:3015', API_URL: process.env.API_URL || 'http://localhost:3015',
}, },
async rewrites() { async rewrites() {
const apiUrl = process.env.API_URL || 'http://localhost:3015';
return [ return [
{ {
source: '/api/:path*', source: '/api/:path*',
destination: `${process.env.API_URL || 'http://api-gateway:3015'}/api/:path*`, destination: `${apiUrl}/api/:path*`,
}, },
]; ];
}, },

View File

@@ -2,32 +2,61 @@
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import Link from 'next/link'; import Link from 'next/link';
import { motion } from 'framer-motion';
import { Sparkles } from 'lucide-react';
import { ForgotPasswordForm } from '@/components/auth'; import { ForgotPasswordForm } from '@/components/auth';
export default function ForgotPasswordPage() { export default function ForgotPasswordPage() {
const router = useRouter(); const router = useRouter();
return ( return (
<div className="min-h-screen bg-base flex flex-col"> <div className="min-h-screen bg-gradient-main flex flex-col relative overflow-hidden">
<header className="p-4"> {/* Background decorations */}
<Link href="/" className="inline-flex items-center gap-2 text-lg font-semibold text-primary"> <div className="absolute inset-0 overflow-hidden pointer-events-none">
<div className="w-8 h-8 rounded-lg bg-accent/20 flex items-center justify-center"> <div className="absolute top-1/4 -left-32 w-96 h-96 bg-accent/5 rounded-full blur-3xl" />
<span className="text-accent font-bold">G</span> <div className="absolute bottom-1/4 -right-32 w-96 h-96 bg-accent-secondary/5 rounded-full blur-3xl" />
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] bg-accent/3 rounded-full blur-3xl" />
</div> </div>
{/* Header */}
<header className="relative z-10 p-6">
<Link href="/" className="inline-flex items-center gap-3 group">
<div className="w-10 h-10 rounded-xl icon-gradient flex items-center justify-center">
<Sparkles className="w-5 h-5 text-accent" />
</div>
<span className="font-black italic text-primary tracking-tight text-2xl group-hover:text-gradient transition-all duration-300">
GooSeek GooSeek
</span>
</Link> </Link>
</header> </header>
<main className="flex-1 flex items-center justify-center px-4 py-8"> {/* Main content */}
<div className="w-full max-w-md"> <main className="relative z-10 flex-1 flex items-center justify-center px-4 py-8">
<div className="bg-elevated border border-border rounded-2xl p-8 shadow-xl"> <motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, ease: 'easeOut' }}
className="w-full max-w-md"
>
{/* Card with gradient border */}
<div className="relative">
<div className="absolute -inset-[1px] bg-gradient-to-r from-accent/30 via-accent-secondary/20 to-accent/30 rounded-2xl blur-sm" />
<div className="relative bg-elevated/95 backdrop-blur-xl border border-border/50 rounded-2xl p-8 shadow-2xl">
<ForgotPasswordForm <ForgotPasswordForm
showTitle showTitle
onBack={() => router.push('/login')} onBack={() => router.push('/login')}
/> />
</div> </div>
</div> </div>
</motion.div>
</main> </main>
{/* Footer */}
<footer className="relative z-10 p-6 text-center">
<p className="text-xs text-faint">
© 2026 GooSeek. Все права защищены.
</p>
</footer>
</div> </div>
); );
} }

View File

@@ -3,6 +3,8 @@
import { useEffect } from 'react'; import { useEffect } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import Link from 'next/link'; import Link from 'next/link';
import { motion } from 'framer-motion';
import { Sparkles } from 'lucide-react';
import { LoginForm } from '@/components/auth'; import { LoginForm } from '@/components/auth';
import { useAuth } from '@/lib/contexts/AuthContext'; import { useAuth } from '@/lib/contexts/AuthContext';
@@ -18,45 +20,78 @@ export default function LoginPage() {
if (isLoading) { if (isLoading) {
return ( return (
<div className="min-h-screen bg-base flex items-center justify-center"> <div className="min-h-screen bg-gradient-main flex items-center justify-center">
<div className="w-8 h-8 border-2 border-accent border-t-transparent rounded-full animate-spin" /> <div className="w-8 h-8 border-2 border-accent border-t-transparent rounded-full animate-spin" />
</div> </div>
); );
} }
return ( return (
<div className="min-h-screen bg-base flex flex-col"> <div className="min-h-screen bg-gradient-main flex flex-col relative overflow-hidden">
<header className="p-4"> {/* Background decorations */}
<Link href="/" className="inline-flex items-center gap-2 text-lg font-semibold text-primary"> <div className="absolute inset-0 overflow-hidden pointer-events-none">
<div className="w-8 h-8 rounded-lg bg-accent/20 flex items-center justify-center"> <div className="absolute top-1/4 -left-32 w-96 h-96 bg-accent/5 rounded-full blur-3xl" />
<span className="text-accent font-bold">G</span> <div className="absolute bottom-1/4 -right-32 w-96 h-96 bg-accent-secondary/5 rounded-full blur-3xl" />
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] bg-accent/3 rounded-full blur-3xl" />
</div> </div>
{/* Header */}
<header className="relative z-10 p-6">
<Link href="/" className="inline-flex items-center gap-3 group">
<div className="w-10 h-10 rounded-xl icon-gradient flex items-center justify-center">
<Sparkles className="w-5 h-5 text-accent" />
</div>
<span className="font-black italic text-primary tracking-tight text-2xl group-hover:text-gradient transition-all duration-300">
GooSeek GooSeek
</span>
</Link> </Link>
</header> </header>
<main className="flex-1 flex items-center justify-center px-4 py-8"> {/* Main content */}
<div className="w-full max-w-md"> <main className="relative z-10 flex-1 flex items-center justify-center px-4 py-8">
<div className="bg-elevated border border-border rounded-2xl p-8 shadow-xl"> <motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, ease: 'easeOut' }}
className="w-full max-w-md"
>
{/* Card with gradient border */}
<div className="relative">
<div className="absolute -inset-[1px] bg-gradient-to-r from-accent/30 via-accent-secondary/20 to-accent/30 rounded-2xl blur-sm" />
<div className="relative bg-elevated/95 backdrop-blur-xl border border-border/50 rounded-2xl p-8 shadow-2xl">
<LoginForm <LoginForm
showTitle showTitle
onSuccess={() => router.push('/')} onSuccess={() => router.push('/')}
onSwitchToRegister={() => router.push('/register')} onSwitchToRegister={() => router.push('/register')}
/> />
</div> </div>
</div>
<p className="text-center text-sm text-muted mt-6"> {/* Footer text */}
<motion.p
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.2, duration: 0.4 }}
className="text-center text-sm text-muted mt-6"
>
Продолжая, вы соглашаетесь с{' '} Продолжая, вы соглашаетесь с{' '}
<Link href="/terms" className="text-accent hover:text-accent-hover"> <Link href="/terms" className="text-accent hover:text-accent-hover transition-colors">
условиями условиями
</Link>{' '} </Link>{' '}
и{' '} и{' '}
<Link href="/privacy" className="text-accent hover:text-accent-hover"> <Link href="/privacy" className="text-accent hover:text-accent-hover transition-colors">
политикой конфиденциальности политикой конфиденциальности
</Link> </Link>
</p> </motion.p>
</div> </motion.div>
</main> </main>
{/* Footer */}
<footer className="relative z-10 p-6 text-center">
<p className="text-xs text-faint">
© 2026 GooSeek. Все права защищены.
</p>
</footer>
</div> </div>
); );
} }

View File

@@ -3,6 +3,8 @@
import { useEffect } from 'react'; import { useEffect } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import Link from 'next/link'; import Link from 'next/link';
import { motion } from 'framer-motion';
import { Sparkles } from 'lucide-react';
import { RegisterForm } from '@/components/auth'; import { RegisterForm } from '@/components/auth';
import { useAuth } from '@/lib/contexts/AuthContext'; import { useAuth } from '@/lib/contexts/AuthContext';
@@ -18,41 +20,74 @@ export default function RegisterPage() {
if (isLoading) { if (isLoading) {
return ( return (
<div className="min-h-screen bg-base flex items-center justify-center"> <div className="min-h-screen bg-gradient-main flex items-center justify-center">
<div className="w-8 h-8 border-2 border-accent border-t-transparent rounded-full animate-spin" /> <div className="w-8 h-8 border-2 border-accent border-t-transparent rounded-full animate-spin" />
</div> </div>
); );
} }
return ( return (
<div className="min-h-screen bg-base flex flex-col"> <div className="min-h-screen bg-gradient-main flex flex-col relative overflow-hidden">
<header className="p-4"> {/* Background decorations */}
<Link href="/" className="inline-flex items-center gap-2 text-lg font-semibold text-primary"> <div className="absolute inset-0 overflow-hidden pointer-events-none">
<div className="w-8 h-8 rounded-lg bg-accent/20 flex items-center justify-center"> <div className="absolute top-1/4 -left-32 w-96 h-96 bg-accent/5 rounded-full blur-3xl" />
<span className="text-accent font-bold">G</span> <div className="absolute bottom-1/4 -right-32 w-96 h-96 bg-accent-secondary/5 rounded-full blur-3xl" />
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] bg-accent/3 rounded-full blur-3xl" />
</div> </div>
{/* Header */}
<header className="relative z-10 p-6">
<Link href="/" className="inline-flex items-center gap-3 group">
<div className="w-10 h-10 rounded-xl icon-gradient flex items-center justify-center">
<Sparkles className="w-5 h-5 text-accent" />
</div>
<span className="font-black italic text-primary tracking-tight text-2xl group-hover:text-gradient transition-all duration-300">
GooSeek GooSeek
</span>
</Link> </Link>
</header> </header>
<main className="flex-1 flex items-center justify-center px-4 py-8"> {/* Main content */}
<div className="w-full max-w-md"> <main className="relative z-10 flex-1 flex items-center justify-center px-4 py-8">
<div className="bg-elevated border border-border rounded-2xl p-8 shadow-xl"> <motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, ease: 'easeOut' }}
className="w-full max-w-md"
>
{/* Card with gradient border */}
<div className="relative">
<div className="absolute -inset-[1px] bg-gradient-to-r from-accent/30 via-accent-secondary/20 to-accent/30 rounded-2xl blur-sm" />
<div className="relative bg-elevated/95 backdrop-blur-xl border border-border/50 rounded-2xl p-8 shadow-2xl">
<RegisterForm <RegisterForm
showTitle showTitle
onSuccess={() => router.push('/')} onSuccess={() => router.push('/')}
onSwitchToLogin={() => router.push('/login')} onSwitchToLogin={() => router.push('/login')}
/> />
</div> </div>
</div>
<p className="text-center text-sm text-muted mt-6"> {/* Footer text */}
<motion.p
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.2, duration: 0.4 }}
className="text-center text-sm text-muted mt-6"
>
Уже есть аккаунт?{' '} Уже есть аккаунт?{' '}
<Link href="/login" className="text-accent hover:text-accent-hover font-medium"> <Link href="/login" className="text-accent hover:text-accent-hover font-medium transition-colors">
Войти Войти
</Link> </Link>
</p> </motion.p>
</div> </motion.div>
</main> </main>
{/* Footer */}
<footer className="relative z-10 p-6 text-center">
<p className="text-xs text-faint">
© 2026 GooSeek. Все права защищены.
</p>
</footer>
</div> </div>
); );
} }

View File

@@ -3,7 +3,8 @@
import { useState, FormEvent, Suspense } from 'react'; import { useState, FormEvent, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation'; import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link'; import Link from 'next/link';
import { Lock, Loader2, Eye, EyeOff, CheckCircle, AlertCircle } from 'lucide-react'; import { motion } from 'framer-motion';
import { Lock, Loader2, Eye, EyeOff, CheckCircle, AlertCircle, Sparkles, Check, X } from 'lucide-react';
import { resetPassword } from '@/lib/auth'; import { resetPassword } from '@/lib/auth';
function ResetPasswordContent() { function ResetPasswordContent() {
@@ -18,6 +19,13 @@ function ResetPasswordContent() {
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [isSuccess, setIsSuccess] = useState(false); const [isSuccess, setIsSuccess] = useState(false);
const passwordRequirements = [
{ met: password.length >= 8, text: 'Минимум 8 символов' },
{ met: /[A-Z]/.test(password), text: 'Заглавная буква' },
{ met: /[a-z]/.test(password), text: 'Строчная буква' },
{ met: /[0-9]/.test(password), text: 'Цифра' },
];
const isPasswordValid = password.length >= 8; const isPasswordValid = password.length >= 8;
const doPasswordsMatch = password === confirmPassword && confirmPassword.length > 0; const doPasswordsMatch = password === confirmPassword && confirmPassword.length > 0;
@@ -64,7 +72,7 @@ function ResetPasswordContent() {
</p> </p>
<Link <Link
href="/forgot-password" href="/forgot-password"
className="inline-flex items-center gap-2 px-4 py-2 bg-accent hover:bg-accent-hover text-white font-medium rounded-xl transition-colors" className="inline-flex items-center gap-2 px-5 py-2.5 bg-accent hover:bg-accent-hover text-white font-medium rounded-xl transition-all duration-200"
> >
Запросить новую ссылку Запросить новую ссылку
</Link> </Link>
@@ -74,7 +82,12 @@ function ResetPasswordContent() {
if (isSuccess) { if (isSuccess) {
return ( return (
<div className="text-center py-6"> <motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3 }}
className="text-center py-6"
>
<div className="w-16 h-16 mx-auto mb-4 rounded-full bg-success/10 flex items-center justify-center"> <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-success/10 flex items-center justify-center">
<CheckCircle className="w-8 h-8 text-success" /> <CheckCircle className="w-8 h-8 text-success" />
</div> </div>
@@ -84,11 +97,11 @@ function ResetPasswordContent() {
</p> </p>
<button <button
onClick={() => router.push('/login')} onClick={() => router.push('/login')}
className="inline-flex items-center gap-2 px-4 py-2 bg-accent hover:bg-accent-hover text-white font-medium rounded-xl transition-colors" className="inline-flex items-center gap-2 px-5 py-2.5 bg-accent hover:bg-accent-hover text-white font-medium rounded-xl transition-all duration-200"
> >
Войти Войти
</button> </button>
</div> </motion.div>
); );
} }
@@ -100,9 +113,13 @@ function ResetPasswordContent() {
</div> </div>
{error && ( {error && (
<div className="p-3 rounded-xl bg-error/10 border border-error/30 text-error text-sm"> <motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
className="p-3 rounded-xl bg-error/10 border border-error/30 text-error text-sm"
>
{error} {error}
</div> </motion.div>
)} )}
<div className="space-y-4"> <div className="space-y-4">
@@ -133,6 +150,22 @@ function ResetPasswordContent() {
{showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />} {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
</button> </button>
</div> </div>
{password.length > 0 && (
<div className="mt-2 grid grid-cols-2 gap-1">
{passwordRequirements.map((req, i) => (
<div
key={i}
className={`flex items-center gap-1.5 text-xs ${
req.met ? 'text-success' : 'text-muted'
}`}
>
{req.met ? <Check className="w-3 h-3" /> : <X className="w-3 h-3" />}
{req.text}
</div>
))}
</div>
)}
</div> </div>
<div> <div>
@@ -149,11 +182,26 @@ function ResetPasswordContent() {
placeholder="••••••••" placeholder="••••••••"
required required
autoComplete="new-password" autoComplete="new-password"
className="w-full pl-11 pr-4 py-3 bg-surface/50 border border-border rounded-xl className={`w-full pl-11 pr-11 py-3 bg-surface/50 border rounded-xl
text-primary placeholder:text-muted text-primary placeholder:text-muted
focus:outline-none focus:border-accent/50 focus:ring-1 focus:ring-accent/20 focus:outline-none focus:ring-1 transition-all duration-200
transition-all duration-200" ${
confirmPassword.length > 0
? doPasswordsMatch
? 'border-success/50 focus:border-success/50 focus:ring-success/20'
: 'border-error/50 focus:border-error/50 focus:ring-error/20'
: 'border-border focus:border-accent/50 focus:ring-accent/20'
}`}
/> />
{confirmPassword.length > 0 && (
<span className="absolute right-3 top-1/2 -translate-y-1/2">
{doPasswordsMatch ? (
<Check className="w-5 h-5 text-success" />
) : (
<X className="w-5 h-5 text-error" />
)}
</span>
)}
</div> </div>
</div> </div>
</div> </div>
@@ -180,19 +228,38 @@ function ResetPasswordContent() {
export default function ResetPasswordPage() { export default function ResetPasswordPage() {
return ( return (
<div className="min-h-screen bg-base flex flex-col"> <div className="min-h-screen bg-gradient-main flex flex-col relative overflow-hidden">
<header className="p-4"> {/* Background decorations */}
<Link href="/" className="inline-flex items-center gap-2 text-lg font-semibold text-primary"> <div className="absolute inset-0 overflow-hidden pointer-events-none">
<div className="w-8 h-8 rounded-lg bg-accent/20 flex items-center justify-center"> <div className="absolute top-1/4 -left-32 w-96 h-96 bg-accent/5 rounded-full blur-3xl" />
<span className="text-accent font-bold">G</span> <div className="absolute bottom-1/4 -right-32 w-96 h-96 bg-accent-secondary/5 rounded-full blur-3xl" />
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] bg-accent/3 rounded-full blur-3xl" />
</div> </div>
{/* Header */}
<header className="relative z-10 p-6">
<Link href="/" className="inline-flex items-center gap-3 group">
<div className="w-10 h-10 rounded-xl icon-gradient flex items-center justify-center">
<Sparkles className="w-5 h-5 text-accent" />
</div>
<span className="font-black italic text-primary tracking-tight text-2xl group-hover:text-gradient transition-all duration-300">
GooSeek GooSeek
</span>
</Link> </Link>
</header> </header>
<main className="flex-1 flex items-center justify-center px-4 py-8"> {/* Main content */}
<div className="w-full max-w-md"> <main className="relative z-10 flex-1 flex items-center justify-center px-4 py-8">
<div className="bg-elevated border border-border rounded-2xl p-8 shadow-xl"> <motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, ease: 'easeOut' }}
className="w-full max-w-md"
>
{/* Card with gradient border */}
<div className="relative">
<div className="absolute -inset-[1px] bg-gradient-to-r from-accent/30 via-accent-secondary/20 to-accent/30 rounded-2xl blur-sm" />
<div className="relative bg-elevated/95 backdrop-blur-xl border border-border/50 rounded-2xl p-8 shadow-2xl">
<Suspense fallback={ <Suspense fallback={
<div className="flex items-center justify-center py-12"> <div className="flex items-center justify-center py-12">
<Loader2 className="w-8 h-8 animate-spin text-accent" /> <Loader2 className="w-8 h-8 animate-spin text-accent" />
@@ -202,7 +269,15 @@ export default function ResetPasswordPage() {
</Suspense> </Suspense>
</div> </div>
</div> </div>
</motion.div>
</main> </main>
{/* Footer */}
<footer className="relative z-10 p-6 text-center">
<p className="text-xs text-faint">
© 2026 GooSeek. Все права защищены.
</p>
</footer>
</div> </div>
); );
} }

View File

@@ -60,11 +60,11 @@ export default function MainLayout({ children }: { children: React.ReactNode })
className="fixed inset-0 z-40 bg-base/80 backdrop-blur-sm" className="fixed inset-0 z-40 bg-base/80 backdrop-blur-sm"
/> />
<motion.div <motion.div
initial={{ x: -280 }} initial={{ x: -240 }}
animate={{ x: 0 }} animate={{ x: 0 }}
exit={{ x: -280 }} exit={{ x: -240 }}
transition={{ type: 'spring', damping: 25, stiffness: 300 }} transition={{ type: 'spring', damping: 25, stiffness: 300 }}
className="fixed left-0 top-0 bottom-0 z-50 w-[280px]" className="fixed left-0 top-0 bottom-0 z-50 w-[240px]"
> >
<Sidebar onClose={() => setSidebarOpen(false)} /> <Sidebar onClose={() => setSidebarOpen(false)} />
</motion.div> </motion.div>

View File

@@ -1,209 +1,124 @@
'use client'; 'use client';
import { useState } from 'react'; import { useState, useEffect } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { motion } from 'framer-motion'; import { motion } from 'framer-motion';
import { Shield, Zap, Scale, Sparkles, Download, Trash2, Bell, Eye, Languages, Plug, ChevronDown } from 'lucide-react'; import { User, CreditCard, Settings, LogIn } from 'lucide-react';
import * as Switch from '@radix-ui/react-switch'; import { useAuth } from '@/lib/contexts/AuthContext';
import { useLanguage, SupportedLanguage } from '@/lib/contexts/LanguageContext'; import { AccountTab } from '@/components/settings/AccountTab';
import { ConnectorsSettings } from '@/components/settings/ConnectorsSettings'; import { BillingTab } from '@/components/settings/BillingTab';
import { PreferencesTab } from '@/components/settings/PreferencesTab';
type TabId = 'account' | 'billing' | 'preferences';
interface Tab {
id: TabId;
label: string;
icon: React.ElementType;
requiresAuth: boolean;
}
const tabs: Tab[] = [
{ id: 'account', label: 'Аккаунт', icon: User, requiresAuth: true },
{ id: 'billing', label: 'Оплата', icon: CreditCard, requiresAuth: true },
{ id: 'preferences', label: 'Настройки', icon: Settings, requiresAuth: false },
];
export default function SettingsPage() { export default function SettingsPage() {
const [mode, setMode] = useState('balanced'); const searchParams = useSearchParams();
const [saveHistory, setSaveHistory] = useState(true); const router = useRouter();
const [personalization, setPersonalization] = useState(true); const { user, isAuthenticated, isLoading, showAuthModal } = useAuth();
const [notifications, setNotifications] = useState(false);
const [showConnectors, setShowConnectors] = useState(false); const tabParam = searchParams.get('tab') as TabId | null;
const { language, setLanguage } = useLanguage(); const [activeTab, setActiveTab] = useState<TabId>(tabParam && tabs.some(t => t.id === tabParam) ? tabParam : 'preferences');
useEffect(() => {
if (tabParam && tabs.some(t => t.id === tabParam)) {
setActiveTab(tabParam);
}
}, [tabParam]);
const handleTabChange = (tabId: TabId) => {
const tab = tabs.find(t => t.id === tabId);
if (tab?.requiresAuth && !isAuthenticated) {
showAuthModal('login');
return;
}
setActiveTab(tabId);
router.push(`/settings?tab=${tabId}`, { scroll: false });
};
const currentTab = tabs.find(t => t.id === activeTab);
const showAuthPrompt = currentTab?.requiresAuth && !isAuthenticated && !isLoading;
return ( return (
<div className="h-full overflow-y-auto"> <div className="h-full overflow-y-auto">
<div className="max-w-xl mx-auto px-4 sm:px-6 py-6 sm:py-8"> <div className="max-w-2xl mx-auto px-4 sm:px-6 py-6 sm:py-8">
{/* Header */} {/* Header */}
<div className="mb-6 sm:mb-8"> <div className="mb-6">
<h1 className="text-xl sm:text-2xl font-semibold text-primary mb-1 sm:mb-2">Настройки</h1> <h1 className="text-xl sm:text-2xl font-semibold text-primary mb-1">
<p className="text-sm text-secondary">Персонализируйте ваш опыт</p> {activeTab === 'account' ? 'Аккаунт' : activeTab === 'billing' ? 'Оплата' : 'Настройки'}
</h1>
<p className="text-sm text-secondary">
{activeTab === 'account'
? 'Управление профилем и безопасностью'
: activeTab === 'billing'
? 'Баланс, тарифы и история платежей'
: 'Персонализируйте ваш опыт'}
</p>
</div> </div>
<div className="space-y-6 sm:space-y-8"> {/* Tabs */}
{/* Default Mode */} <div className="flex gap-1 p-1 bg-surface/30 border border-border/30 rounded-xl mb-6">
<Section title="Режим по умолчанию" icon={Zap}> {tabs.map((tab) => (
<div className="grid grid-cols-3 gap-2 sm:gap-3">
{[
{ id: 'speed', label: 'Быстрый', icon: Zap, desc: '~10 сек' },
{ id: 'balanced', label: 'Баланс', icon: Scale, desc: '~30 сек' },
{ id: 'quality', label: 'Качество', icon: Sparkles, desc: '~60 сек' },
].map((m) => (
<button <button
key={m.id} key={tab.id}
onClick={() => setMode(m.id)} onClick={() => handleTabChange(tab.id)}
className={`flex flex-col items-center gap-1 sm:gap-2 p-3 sm:p-4 rounded-xl border transition-all ${ className={`flex-1 flex items-center justify-center gap-2 py-2.5 px-3 rounded-lg text-sm font-medium transition-all ${
mode === m.id activeTab === tab.id
? 'active-gradient text-primary' ? 'bg-base text-primary shadow-sm'
: 'bg-surface/30 border-border/30 text-muted hover:border-border hover:text-secondary' : 'text-muted hover:text-secondary'
}`} }`}
> >
<m.icon className={`w-4 h-4 sm:w-5 sm:h-5 ${mode === m.id ? 'text-gradient' : ''}`} /> <tab.icon className="w-4 h-4" />
<span className="text-xs sm:text-sm font-medium">{m.label}</span> <span className="hidden sm:inline">{tab.label}</span>
<span className="text-[10px] sm:text-xs text-faint">{m.desc}</span>
</button> </button>
))} ))}
</div> </div>
</Section>
{/* Privacy & Data */} {/* Content */}
<Section title="Приватность" icon={Shield}> <motion.div
<div className="space-y-3"> key={activeTab}
<ToggleRow initial={{ opacity: 0, y: 10 }}
icon={Eye} animate={{ opacity: 1, y: 0 }}
label="Сохранять историю" transition={{ duration: 0.2 }}
description="Автоматическое сохранение сессий"
checked={saveHistory}
onChange={setSaveHistory}
/>
<ToggleRow
icon={Sparkles}
label="Персонализация"
description="Улучшение на основе истории"
checked={personalization}
onChange={setPersonalization}
/>
<ToggleRow
icon={Bell}
label="Уведомления"
description="Уведомления об обновлениях"
checked={notifications}
onChange={setNotifications}
/>
</div>
</Section>
{/* Language */}
<Section title="Язык интерфейса" icon={Languages}>
<div className="grid grid-cols-2 gap-2 sm:gap-3">
{[
{ id: 'ru', label: 'Русский', flag: '🇷🇺' },
{ id: 'en', label: 'English', flag: '🇺🇸' },
].map((lang) => (
<button
key={lang.id}
onClick={() => setLanguage(lang.id as SupportedLanguage)}
className={`flex items-center gap-3 p-3 sm:p-4 rounded-xl border transition-all ${
language === lang.id
? 'active-gradient text-primary'
: 'bg-surface/30 border-border/30 text-muted hover:border-border hover:text-secondary'
}`}
> >
<span className="text-lg">{lang.flag}</span> {showAuthPrompt ? (
<span className="text-sm font-medium">{lang.label}</span> <div className="flex flex-col items-center justify-center py-16">
</button> <div className="w-16 h-16 rounded-full bg-accent/10 flex items-center justify-center mb-4">
))} <LogIn className="w-8 h-8 text-accent" />
</div> </div>
</Section> <h2 className="text-lg font-medium text-primary mb-2">Требуется авторизация</h2>
<p className="text-sm text-muted text-center mb-6 max-w-sm">
{/* Connectors */} Войдите в аккаунт, чтобы получить доступ к {activeTab === 'account' ? 'настройкам профиля' : 'платежам и балансу'}
<Section title="Коннекторы" icon={Plug}>
<div className="space-y-3">
<p className="text-xs text-muted">
Подключите источники данных и каналы уведомлений для автономных задач в Лаптопе.
</p> </p>
<button <button
onClick={() => setShowConnectors(!showConnectors)} onClick={() => showAuthModal('login')}
className="w-full flex items-center justify-between p-3 sm:p-4 bg-elevated/40 border border-border/40 rounded-xl hover:bg-elevated/60 hover:border-border transition-all" className="flex items-center gap-2 px-6 py-2.5 bg-accent text-white rounded-xl hover:bg-accent-hover transition-all text-sm font-medium"
> >
<div className="flex items-center gap-3"> <LogIn className="w-4 h-4" />
<div className="w-10 h-10 rounded-xl bg-indigo-500/10 flex items-center justify-center"> Войти
<Plug className="w-5 h-5 text-indigo-400" />
</div>
<div className="text-left">
<p className="text-sm font-medium text-primary">Настроить коннекторы</p>
<p className="text-xs text-muted">Поиск, данные, финансы, уведомления</p>
</div>
</div>
<ChevronDown className={`w-5 h-5 text-muted transition-transform ${showConnectors ? 'rotate-180' : ''}`} />
</button> </button>
</div>
{showConnectors && ( ) : (
<motion.div <>
initial={{ opacity: 0, height: 0 }} {activeTab === 'account' && <AccountTab />}
animate={{ opacity: 1, height: 'auto' }} {activeTab === 'billing' && <BillingTab />}
className="pt-2" {activeTab === 'preferences' && <PreferencesTab />}
> </>
<ConnectorsSettings />
</motion.div>
)} )}
</div>
</Section>
{/* Data Management */}
<Section title="Управление данными" icon={Download}>
<div className="flex flex-col sm:flex-row gap-3">
<button className="flex-1 flex items-center justify-center gap-2 px-4 py-3 text-sm bg-surface/40 border border-border/50 text-secondary rounded-xl hover:bg-surface/60 hover:border-border hover:text-primary transition-all">
<Download className="w-4 h-4" />
Экспорт данных
</button>
<button className="flex-1 flex items-center justify-center gap-2 px-4 py-3 text-sm bg-error/5 border border-error/20 text-error rounded-xl hover:bg-error/10 hover:border-error/30 transition-all">
<Trash2 className="w-4 h-4" />
Удалить всё
</button>
</div>
</Section>
{/* About */}
<div className="pt-6 border-t border-border/30">
<div className="text-center text-faint text-xs">
<p className="mb-1">GooSeek v1.0.0</p>
<p>AI-поиск нового поколения</p>
</div>
</div>
</div>
</div>
</div>
);
}
function Section({ title, icon: Icon, children }: { title: string; icon: React.ElementType; children: React.ReactNode }) {
return (
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
className="space-y-3 sm:space-y-4"
>
<div className="flex items-center gap-2">
<Icon className="w-4 h-4 text-muted" />
<h2 className="text-xs font-semibold text-muted uppercase tracking-wider">
{title}
</h2>
</div>
{children}
</motion.div> </motion.div>
);
}
interface ToggleRowProps {
icon: React.ElementType;
label: string;
description: string;
checked: boolean;
onChange: (v: boolean) => void;
}
function ToggleRow({ icon: Icon, label, description, checked, onChange }: ToggleRowProps) {
return (
<div className="flex items-center gap-3 sm:gap-4 p-3 sm:p-4 bg-elevated/40 border border-border/40 rounded-xl">
<div className="w-9 h-9 sm:w-10 sm:h-10 rounded-xl bg-surface/60 flex items-center justify-center flex-shrink-0">
<Icon className="w-4 h-4 text-secondary" />
</div> </div>
<div className="flex-1 min-w-0">
<p className="text-sm text-primary truncate">{label}</p>
<p className="text-xs text-muted mt-0.5 truncate">{description}</p>
</div>
<Switch.Root
checked={checked}
onCheckedChange={onChange}
className="w-10 h-[22px] sm:w-11 sm:h-6 bg-surface/80 rounded-full relative transition-colors data-[state=checked]:active-gradient border border-border flex-shrink-0"
>
<Switch.Thumb className="block w-[18px] h-[18px] sm:w-5 sm:h-5 bg-secondary rounded-full transition-transform translate-x-0.5 data-[state=checked]:translate-x-[18px] sm:data-[state=checked]:translate-x-[22px] data-[state=checked]:progress-gradient" />
</Switch.Root>
</div> </div>
); );
} }

View File

@@ -0,0 +1,466 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { motion, AnimatePresence } from 'framer-motion';
import {
ArrowLeft,
FolderOpen,
Plus,
Users,
MessageSquare,
Settings,
UserPlus,
Loader2,
Clock,
MoreHorizontal,
Trash2,
Crown,
Shield,
User,
Copy,
Check,
X,
Send,
} from 'lucide-react';
import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
import * as Dialog from '@radix-ui/react-dialog';
import { fetchSpace, fetchSpaceMembers, fetchSpaceThreads, inviteToSpace, removeSpaceMember } from '@/lib/api';
import type { Space, SpaceMember, Thread } from '@/lib/types';
import { useAuth } from '@/lib/contexts/AuthContext';
function formatDate(dateStr: string): string {
const date = new Date(dateStr);
const now = new Date();
const diff = now.getTime() - date.getTime();
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
if (days === 0) return 'Сегодня';
if (days === 1) return 'Вчера';
if (days < 7) return `${days} дн. назад`;
return date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' });
}
function getRoleIcon(role: string) {
switch (role) {
case 'owner': return Crown;
case 'admin': return Shield;
default: return User;
}
}
function getRoleLabel(role: string) {
switch (role) {
case 'owner': return 'Владелец';
case 'admin': return 'Админ';
default: return 'Участник';
}
}
export default function SpaceDetailPage() {
const params = useParams();
const router = useRouter();
const { user } = useAuth();
const spaceId = params.id as string;
const [space, setSpace] = useState<Space | null>(null);
const [members, setMembers] = useState<SpaceMember[]>([]);
const [threads, setThreads] = useState<Thread[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [activeTab, setActiveTab] = useState<'threads' | 'members'>('threads');
const [showInviteModal, setShowInviteModal] = useState(false);
const [inviteEmail, setInviteEmail] = useState('');
const [inviteLoading, setInviteLoading] = useState(false);
const [inviteError, setInviteError] = useState('');
const [inviteSuccess, setInviteSuccess] = useState('');
const isOwner = space?.userId === user?.id;
const currentMember = members.find(m => m.userId === user?.id);
const isAdmin = isOwner || currentMember?.role === 'admin';
const loadData = useCallback(async () => {
setIsLoading(true);
try {
const [spaceData, membersData, threadsData] = await Promise.all([
fetchSpace(spaceId),
fetchSpaceMembers(spaceId),
fetchSpaceThreads(spaceId),
]);
setSpace(spaceData);
setMembers(membersData);
setThreads(threadsData);
} catch (err) {
console.error('Failed to load space:', err);
} finally {
setIsLoading(false);
}
}, [spaceId]);
useEffect(() => {
loadData();
}, [loadData]);
const handleInvite = async (e: React.FormEvent) => {
e.preventDefault();
if (!inviteEmail.trim() || inviteLoading) return;
setInviteLoading(true);
setInviteError('');
setInviteSuccess('');
try {
await inviteToSpace(spaceId, inviteEmail.trim());
setInviteSuccess(`Приглашение отправлено на ${inviteEmail}`);
setInviteEmail('');
setTimeout(() => setShowInviteModal(false), 2000);
} catch (err) {
setInviteError(err instanceof Error ? err.message : 'Не удалось отправить приглашение');
} finally {
setInviteLoading(false);
}
};
const handleRemoveMember = async (memberId: string, userId: string) => {
if (!confirm('Удалить участника из пространства?')) return;
try {
await removeSpaceMember(spaceId, userId);
setMembers(prev => prev.filter(m => m.id !== memberId));
} catch (err) {
console.error('Failed to remove member:', err);
}
};
const startNewThread = () => {
router.push(`/?space=${spaceId}`);
};
if (isLoading) {
return (
<div className="flex flex-col items-center justify-center min-h-[60vh]">
<Loader2 className="w-8 h-8 animate-spin loader-gradient" />
<p className="text-sm text-muted mt-4">Загрузка пространства...</p>
</div>
);
}
if (!space) {
return (
<div className="flex flex-col items-center justify-center min-h-[60vh]">
<FolderOpen className="w-12 h-12 text-muted mb-4" />
<h2 className="text-xl font-semibold text-primary mb-2">Пространство не найдено</h2>
<p className="text-secondary mb-6">Возможно, оно было удалено или у вас нет доступа</p>
<Link href="/spaces" className="btn-gradient px-5 py-2.5">
<span className="btn-gradient-text">К списку пространств</span>
</Link>
</div>
);
}
return (
<div className="h-full overflow-y-auto">
<div className="max-w-5xl mx-auto px-4 sm:px-6 py-6 sm:py-8">
{/* Header */}
<div className="flex items-start gap-4 mb-8">
<Link
href="/spaces"
className="w-10 h-10 flex items-center justify-center rounded-xl text-secondary hover:text-primary hover:bg-surface/50 transition-all flex-shrink-0"
>
<ArrowLeft className="w-5 h-5" />
</Link>
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between gap-4">
<div>
<h1 className="text-2xl sm:text-3xl font-bold text-primary mb-2">{space.name}</h1>
{space.description && (
<p className="text-secondary">{space.description}</p>
)}
</div>
<div className="flex items-center gap-2 flex-shrink-0">
{isAdmin && (
<button
onClick={() => setShowInviteModal(true)}
className="flex items-center gap-2 px-4 py-2.5 text-sm btn-gradient"
>
<UserPlus className="w-4 h-4 btn-gradient-text" />
<span className="btn-gradient-text hidden sm:inline">Пригласить</span>
</button>
)}
<Link
href={`/spaces/${spaceId}/edit`}
className="p-2.5 rounded-xl text-secondary hover:text-primary hover:bg-surface/50 transition-all"
>
<Settings className="w-5 h-5" />
</Link>
</div>
</div>
{/* Stats */}
<div className="flex items-center gap-6 mt-4">
<div className="flex items-center gap-2 text-sm text-muted">
<Users className="w-4 h-4" />
<span>{members.length} участник{members.length === 1 ? '' : members.length < 5 ? 'а' : 'ов'}</span>
</div>
<div className="flex items-center gap-2 text-sm text-muted">
<MessageSquare className="w-4 h-4" />
<span>{threads.length} тред{threads.length === 1 ? '' : threads.length < 5 ? 'а' : 'ов'}</span>
</div>
</div>
</div>
</div>
{/* Tabs */}
<div className="flex items-center gap-1 p-1 bg-surface/40 rounded-xl mb-6 w-fit">
<button
onClick={() => setActiveTab('threads')}
className={`px-4 py-2 text-sm font-medium rounded-lg transition-all ${
activeTab === 'threads'
? 'bg-accent/20 text-accent'
: 'text-secondary hover:text-primary'
}`}
>
<span className="flex items-center gap-2">
<MessageSquare className="w-4 h-4" />
Треды
</span>
</button>
<button
onClick={() => setActiveTab('members')}
className={`px-4 py-2 text-sm font-medium rounded-lg transition-all ${
activeTab === 'members'
? 'bg-accent/20 text-accent'
: 'text-secondary hover:text-primary'
}`}
>
<span className="flex items-center gap-2">
<Users className="w-4 h-4" />
Участники
</span>
</button>
</div>
{/* Content */}
<AnimatePresence mode="wait">
{activeTab === 'threads' ? (
<motion.div
key="threads"
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
>
{/* New Thread Button */}
<button
onClick={startNewThread}
className="w-full p-4 mb-4 border-2 border-dashed border-border/50 rounded-xl text-secondary hover:text-primary hover:border-accent/30 hover:bg-accent/5 transition-all flex items-center justify-center gap-2"
>
<Plus className="w-5 h-5" />
<span>Начать новый тред</span>
</button>
{/* Threads List */}
{threads.length > 0 ? (
<div className="space-y-3">
{threads.map((thread, i) => (
<motion.div
key={thread.id}
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: i * 0.03 }}
>
<Link
href={`/thread/${thread.id}`}
className="block p-4 bg-elevated/40 border border-border/40 rounded-xl hover:bg-elevated/60 hover:border-border transition-all group"
>
<h3 className="font-medium text-primary group-hover:text-gradient transition-colors line-clamp-1 mb-2">
{thread.title || 'Без названия'}
</h3>
<div className="flex items-center gap-4 text-xs text-muted">
<span className="flex items-center gap-1.5">
<Clock className="w-3.5 h-3.5" />
{formatDate(thread.updatedAt)}
</span>
<span>{thread.messages?.length || 0} сообщений</span>
</div>
</Link>
</motion.div>
))}
</div>
) : (
<div className="text-center py-12">
<MessageSquare className="w-12 h-12 mx-auto mb-4 text-muted" />
<p className="text-secondary mb-2">Пока нет тредов</p>
<p className="text-sm text-muted">Начните новый тред для обсуждения</p>
</div>
)}
</motion.div>
) : (
<motion.div
key="members"
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
>
{/* Members List */}
<div className="space-y-2">
{members.map((member, i) => {
const RoleIcon = getRoleIcon(member.role);
const canRemove = isAdmin && member.userId !== user?.id && member.role !== 'owner';
return (
<motion.div
key={member.id}
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: i * 0.03 }}
className="flex items-center gap-4 p-4 bg-elevated/40 border border-border/40 rounded-xl"
>
<div className="w-10 h-10 rounded-full bg-accent/20 flex items-center justify-center flex-shrink-0">
{member.avatar ? (
<img src={member.avatar} alt="" className="w-full h-full rounded-full object-cover" />
) : (
<span className="text-sm font-semibold text-accent">
{(member.name || member.email || '?').charAt(0).toUpperCase()}
</span>
)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-medium text-primary truncate">
{member.name || member.email}
</span>
<span className={`flex items-center gap-1 text-xs px-2 py-0.5 rounded-full ${
member.role === 'owner'
? 'bg-amber-500/20 text-amber-400'
: member.role === 'admin'
? 'bg-accent/20 text-accent'
: 'bg-surface text-muted'
}`}>
<RoleIcon className="w-3 h-3" />
{getRoleLabel(member.role)}
</span>
</div>
{member.email && member.name && (
<p className="text-sm text-muted truncate">{member.email}</p>
)}
</div>
{canRemove && (
<DropdownMenu.Root>
<DropdownMenu.Trigger asChild>
<button className="p-2 hover:bg-surface/60 rounded-lg transition-all">
<MoreHorizontal className="w-4 h-4 text-secondary" />
</button>
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content
className="min-w-[140px] bg-surface/95 backdrop-blur-xl border border-border rounded-xl p-1.5 shadow-dropdown z-50"
sideOffset={5}
>
<DropdownMenu.Item
onClick={() => handleRemoveMember(member.id, member.userId)}
className="flex items-center gap-2 px-3 py-2.5 text-sm text-error rounded-lg cursor-pointer hover:bg-error/10 outline-none transition-colors"
>
<Trash2 className="w-4 h-4" />
Удалить
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
)}
</motion.div>
);
})}
</div>
{/* Invite Button */}
{isAdmin && (
<button
onClick={() => setShowInviteModal(true)}
className="w-full mt-4 p-4 border-2 border-dashed border-border/50 rounded-xl text-secondary hover:text-primary hover:border-accent/30 hover:bg-accent/5 transition-all flex items-center justify-center gap-2"
>
<UserPlus className="w-5 h-5" />
<span>Пригласить участника</span>
</button>
)}
</motion.div>
)}
</AnimatePresence>
{/* Invite Modal */}
<Dialog.Root open={showInviteModal} onOpenChange={setShowInviteModal}>
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50" />
<Dialog.Content className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-md bg-elevated border border-border rounded-2xl p-6 z-50 shadow-2xl">
<div className="flex items-center justify-between mb-6">
<Dialog.Title className="text-lg font-semibold text-primary">
Пригласить участника
</Dialog.Title>
<Dialog.Close className="p-2 text-muted hover:text-secondary rounded-lg hover:bg-surface/50 transition-colors">
<X className="w-5 h-5" />
</Dialog.Close>
</div>
<form onSubmit={handleInvite}>
<p className="text-sm text-secondary mb-4">
Введите email пользователя, которого хотите пригласить в пространство
</p>
{inviteError && (
<div className="mb-4 p-3 bg-error/10 border border-error/30 rounded-xl text-sm text-error">
{inviteError}
</div>
)}
{inviteSuccess && (
<div className="mb-4 p-3 bg-success/10 border border-success/30 rounded-xl text-sm text-success flex items-center gap-2">
<Check className="w-4 h-4" />
{inviteSuccess}
</div>
)}
<div className="relative mb-6">
<input
type="email"
value={inviteEmail}
onChange={(e) => setInviteEmail(e.target.value)}
placeholder="email@example.com"
className="w-full px-4 py-3 bg-surface/50 border border-border rounded-xl text-primary placeholder:text-muted focus:outline-none input-gradient transition-colors"
autoFocus
/>
</div>
<div className="flex gap-3">
<Dialog.Close asChild>
<button
type="button"
className="flex-1 px-4 py-3 text-sm text-secondary hover:text-primary bg-surface/40 border border-border/50 rounded-xl transition-all"
>
Отмена
</button>
</Dialog.Close>
<button
type="submit"
disabled={!inviteEmail.trim() || inviteLoading}
className="flex-1 flex items-center justify-center gap-2 px-4 py-3 text-sm btn-gradient disabled:opacity-50"
>
{inviteLoading ? (
<Loader2 className="w-4 h-4 animate-spin btn-gradient-text" />
) : (
<Send className="w-4 h-4 btn-gradient-text" />
)}
<span className="btn-gradient-text">Отправить</span>
</button>
</div>
</form>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
</div>
</div>
);
}

View File

@@ -3,19 +3,28 @@
import { useState } from 'react'; import { useState } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import Link from 'next/link'; import Link from 'next/link';
import { ArrowLeft, Loader2, Globe, BookOpen, Code2, Newspaper, TrendingUp, Youtube } from 'lucide-react'; import { motion } from 'framer-motion';
import {
ArrowLeft,
Loader2,
Globe,
Lock,
FolderOpen,
Palette,
} from 'lucide-react';
import { createSpace } from '@/lib/api'; import { createSpace } from '@/lib/api';
import type { FocusMode } from '@/lib/types';
const focusModes: { value: FocusMode; label: string; icon: React.ElementType }[] = [ const spaceColors = [
{ value: 'all', label: 'Все источники', icon: Globe }, { id: 'violet', class: 'bg-violet-500', label: 'Фиолетовый' },
{ value: 'academic', label: 'Академический', icon: BookOpen }, { id: 'blue', class: 'bg-blue-500', label: 'Синий' },
{ value: 'code', label: 'Код', icon: Code2 }, { id: 'emerald', class: 'bg-emerald-500', label: 'Изумрудный' },
{ value: 'news', label: 'Новости', icon: Newspaper }, { id: 'orange', class: 'bg-orange-500', label: 'Оранжевый' },
{ value: 'finance', label: 'Финансы', icon: TrendingUp }, { id: 'pink', class: 'bg-pink-500', label: 'Розовый' },
{ value: 'youtube', label: 'YouTube', icon: Youtube }, { id: 'indigo', class: 'bg-indigo-500', label: 'Индиго' },
]; ];
const spaceIcons = ['📁', '🔬', '💡', '📊', '🎯', '🚀', '💼', '📚'];
export default function NewSpacePage() { export default function NewSpacePage() {
const router = useRouter(); const router = useRouter();
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
@@ -25,7 +34,9 @@ export default function NewSpacePage() {
name: '', name: '',
description: '', description: '',
instructions: '', instructions: '',
focusMode: 'all' as FocusMode, icon: '📁',
color: 'violet',
isPublic: false,
}); });
const handleCreate = async (e: React.FormEvent) => { const handleCreate = async (e: React.FormEvent) => {
@@ -36,13 +47,12 @@ export default function NewSpacePage() {
setError(null); setError(null);
try { try {
await createSpace({ const space = await createSpace({
name: formData.name.trim(), name: formData.name.trim(),
description: formData.description.trim() || undefined, description: formData.description.trim() || undefined,
instructions: formData.instructions.trim() || undefined, instructions: formData.instructions.trim() || undefined,
focusMode: formData.focusMode,
}); });
router.push('/spaces'); router.push(`/spaces/${space.id}`);
} catch (err) { } catch (err) {
console.error('Failed to create space:', err); console.error('Failed to create space:', err);
setError('Не удалось создать пространство. Попробуйте позже.'); setError('Не удалось создать пространство. Попробуйте позже.');
@@ -53,9 +63,9 @@ export default function NewSpacePage() {
return ( return (
<div className="h-full overflow-y-auto"> <div className="h-full overflow-y-auto">
<div className="max-w-lg mx-auto px-4 sm:px-6 py-6 sm:py-8"> <div className="max-w-xl mx-auto px-4 sm:px-6 py-6 sm:py-8">
{/* Header */} {/* Header */}
<div className="flex items-center gap-4 mb-6 sm:mb-8"> <div className="flex items-center gap-4 mb-8">
<Link <Link
href="/spaces" href="/spaces"
className="w-10 h-10 flex items-center justify-center rounded-xl text-secondary hover:text-primary hover:bg-surface/50 transition-all" className="w-10 h-10 flex items-center justify-center rounded-xl text-secondary hover:text-primary hover:bg-surface/50 transition-all"
@@ -63,19 +73,53 @@ export default function NewSpacePage() {
<ArrowLeft className="w-5 h-5" /> <ArrowLeft className="w-5 h-5" />
</Link> </Link>
<div> <div>
<h1 className="text-xl sm:text-2xl font-semibold text-primary">Новое пространство</h1> <h1 className="text-2xl font-bold text-primary">Новое пространство</h1>
<p className="text-sm text-secondary mt-0.5 hidden sm:block">Организуйте исследования по темам</p> <p className="text-sm text-secondary mt-0.5">Создайте место для исследований и коллаборации</p>
</div> </div>
</div> </div>
{error && ( {error && (
<div className="mb-6 p-4 bg-error/10 border border-error/30 rounded-xl text-sm text-error"> <motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
className="mb-6 p-4 bg-error/10 border border-error/30 rounded-xl text-sm text-error"
>
{error} {error}
</div> </motion.div>
)} )}
{/* Form */} {/* Form */}
<form onSubmit={handleCreate} className="space-y-5"> <form onSubmit={handleCreate} className="space-y-6">
{/* Preview Card */}
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
className={`
p-6 rounded-2xl border bg-gradient-to-br
${formData.color === 'violet' ? 'from-violet-500/20 to-purple-500/20 border-violet-500/30' : ''}
${formData.color === 'blue' ? 'from-blue-500/20 to-cyan-500/20 border-blue-500/30' : ''}
${formData.color === 'emerald' ? 'from-emerald-500/20 to-teal-500/20 border-emerald-500/30' : ''}
${formData.color === 'orange' ? 'from-orange-500/20 to-amber-500/20 border-orange-500/30' : ''}
${formData.color === 'pink' ? 'from-pink-500/20 to-rose-500/20 border-pink-500/30' : ''}
${formData.color === 'indigo' ? 'from-indigo-500/20 to-blue-500/20 border-indigo-500/30' : ''}
`}
>
<div className="flex items-center gap-4">
<div className="w-14 h-14 rounded-xl bg-white/10 backdrop-blur-sm flex items-center justify-center text-2xl">
{formData.icon}
</div>
<div>
<h3 className="text-lg font-semibold text-primary">
{formData.name || 'Название пространства'}
</h3>
<p className="text-sm text-secondary">
{formData.description || 'Описание пространства'}
</p>
</div>
</div>
</motion.div>
{/* Name */}
<div> <div>
<label className="block text-sm font-medium text-secondary mb-2"> <label className="block text-sm font-medium text-secondary mb-2">
Название <span className="text-error">*</span> Название <span className="text-error">*</span>
@@ -83,12 +127,13 @@ export default function NewSpacePage() {
<input <input
value={formData.name} value={formData.name}
onChange={(e) => setFormData((f) => ({ ...f, name: e.target.value }))} onChange={(e) => setFormData((f) => ({ ...f, name: e.target.value }))}
placeholder="Например: Исследование рынка" placeholder="Например: Исследование рынка AI"
className="w-full px-4 py-3 text-sm bg-elevated/60 border border-border rounded-xl text-primary placeholder:text-muted focus:outline-none input-gradient transition-colors" className="w-full px-4 py-3.5 text-sm bg-elevated/60 border border-border rounded-xl text-primary placeholder:text-muted focus:outline-none input-gradient transition-colors"
autoFocus autoFocus
/> />
</div> </div>
{/* Description */}
<div> <div>
<label className="block text-sm font-medium text-secondary mb-2"> <label className="block text-sm font-medium text-secondary mb-2">
Описание Описание
@@ -96,12 +141,58 @@ export default function NewSpacePage() {
<textarea <textarea
value={formData.description} value={formData.description}
onChange={(e) => setFormData((f) => ({ ...f, description: e.target.value }))} onChange={(e) => setFormData((f) => ({ ...f, description: e.target.value }))}
placeholder="Краткое описание пространства" placeholder="О чём это пространство? Какие цели преследует?"
rows={2} rows={3}
className="w-full px-4 py-3 text-sm bg-elevated/60 border border-border rounded-xl text-primary placeholder:text-muted resize-none focus:outline-none input-gradient transition-colors" className="w-full px-4 py-3.5 text-sm bg-elevated/60 border border-border rounded-xl text-primary placeholder:text-muted resize-none focus:outline-none input-gradient transition-colors"
/> />
</div> </div>
{/* Icon Selector */}
<div>
<label className="block text-sm font-medium text-secondary mb-3">
Иконка
</label>
<div className="flex flex-wrap gap-2">
{spaceIcons.map((icon) => (
<button
key={icon}
type="button"
onClick={() => setFormData((f) => ({ ...f, icon }))}
className={`w-10 h-10 rounded-xl text-lg flex items-center justify-center transition-all ${
formData.icon === icon
? 'bg-accent/20 ring-2 ring-accent'
: 'bg-surface/40 hover:bg-surface/60'
}`}
>
{icon}
</button>
))}
</div>
</div>
{/* Color Selector */}
<div>
<label className="block text-sm font-medium text-secondary mb-3">
Цвет
</label>
<div className="flex flex-wrap gap-2">
{spaceColors.map((color) => (
<button
key={color.id}
type="button"
onClick={() => setFormData((f) => ({ ...f, color: color.id }))}
className={`w-10 h-10 rounded-xl ${color.class} transition-all ${
formData.color === color.id
? 'ring-2 ring-white ring-offset-2 ring-offset-base'
: 'opacity-60 hover:opacity-100'
}`}
title={color.label}
/>
))}
</div>
</div>
{/* AI Instructions */}
<div> <div>
<label className="block text-sm font-medium text-secondary mb-2"> <label className="block text-sm font-medium text-secondary mb-2">
AI инструкции AI инструкции
@@ -109,32 +200,48 @@ export default function NewSpacePage() {
<textarea <textarea
value={formData.instructions} value={formData.instructions}
onChange={(e) => setFormData((f) => ({ ...f, instructions: e.target.value }))} onChange={(e) => setFormData((f) => ({ ...f, instructions: e.target.value }))}
placeholder="Специальные инструкции для AI в этом пространстве" placeholder="Дополнительные инструкции для AI при работе в этом пространстве"
rows={3} rows={3}
className="w-full px-4 py-3 text-sm bg-elevated/60 border border-border rounded-xl text-primary placeholder:text-muted resize-none focus:outline-none input-gradient transition-colors" className="w-full px-4 py-3.5 text-sm bg-elevated/60 border border-border rounded-xl text-primary placeholder:text-muted resize-none focus:outline-none input-gradient transition-colors"
/> />
<p className="text-xs text-muted mt-2">
AI будет учитывать эти инструкции при генерации ответов в тредах этого пространства
</p>
</div> </div>
{/* Privacy */}
<div className="p-4 bg-elevated/40 border border-border/50 rounded-xl">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
{formData.isPublic ? (
<Globe className="w-5 h-5 text-accent" />
) : (
<Lock className="w-5 h-5 text-muted" />
)}
<div> <div>
<label className="block text-sm font-medium text-secondary mb-3"> <h4 className="text-sm font-medium text-primary">
Режим фокуса {formData.isPublic ? 'Публичное' : 'Приватное'}
</label> </h4>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2"> <p className="text-xs text-muted">
{focusModes.map((mode) => ( {formData.isPublic
? 'Все могут найти и присоединиться'
: 'Только по приглашению'}
</p>
</div>
</div>
<button <button
key={mode.value}
type="button" type="button"
onClick={() => setFormData((f) => ({ ...f, focusMode: mode.value }))} onClick={() => setFormData((f) => ({ ...f, isPublic: !f.isPublic }))}
className={`flex flex-col items-center gap-2 p-3 rounded-xl border transition-all ${ className={`w-12 h-7 rounded-full transition-colors relative ${
formData.focusMode === mode.value formData.isPublic ? 'bg-accent' : 'bg-surface'
? 'active-gradient text-primary'
: 'bg-elevated/40 border-border/50 text-muted hover:border-border hover:text-secondary'
}`} }`}
> >
<mode.icon className={`w-4 h-4 ${formData.focusMode === mode.value ? 'text-gradient' : ''}`} /> <span
<span className="text-xs text-center">{mode.label}</span> className={`absolute top-1 w-5 h-5 rounded-full bg-white shadow transition-transform ${
formData.isPublic ? 'translate-x-6' : 'translate-x-1'
}`}
/>
</button> </button>
))}
</div> </div>
</div> </div>
@@ -142,17 +249,21 @@ export default function NewSpacePage() {
<div className="flex flex-col-reverse sm:flex-row gap-3 pt-4"> <div className="flex flex-col-reverse sm:flex-row gap-3 pt-4">
<Link <Link
href="/spaces" href="/spaces"
className="flex-1 px-4 py-3 text-sm text-center text-secondary hover:text-primary bg-surface/40 border border-border/50 rounded-xl transition-all" className="flex-1 px-4 py-3.5 text-sm text-center text-secondary hover:text-primary bg-surface/40 border border-border/50 rounded-xl transition-all"
> >
Отмена Отмена
</Link> </Link>
<button <button
type="submit" type="submit"
disabled={!formData.name.trim() || isSubmitting} disabled={!formData.name.trim() || isSubmitting}
className="flex-1 flex items-center justify-center gap-2 px-4 py-3 text-sm btn-gradient disabled:opacity-50" className="flex-1 flex items-center justify-center gap-2 px-4 py-3.5 text-sm btn-gradient disabled:opacity-50"
> >
{isSubmitting && <Loader2 className="w-4 h-4 animate-spin btn-gradient-text" />} {isSubmitting ? (
<span className="btn-gradient-text">Создать пространство</span> <Loader2 className="w-4 h-4 animate-spin btn-gradient-text" />
) : (
<FolderOpen className="w-4 h-4 btn-gradient-text" />
)}
<span className="btn-gradient-text font-medium">Создать пространство</span>
</button> </button>
</div> </div>
</form> </form>

View File

@@ -4,27 +4,50 @@ import { useState, useEffect, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import Link from 'next/link'; import Link from 'next/link';
import { motion } from 'framer-motion'; import { motion } from 'framer-motion';
import { FolderOpen, Plus, MoreHorizontal, Search, Trash2, Loader2, Settings, RefreshCw, Globe, BookOpen, Code2, TrendingUp, Newspaper, Youtube } from 'lucide-react'; import {
FolderOpen,
Plus,
Search,
Loader2,
Users,
MessageSquare,
Lock,
Globe,
MoreHorizontal,
Trash2,
Settings,
UserPlus,
} from 'lucide-react';
import * as DropdownMenu from '@radix-ui/react-dropdown-menu'; import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
import { fetchSpaces, deleteSpace } from '@/lib/api'; import { fetchSpaces, deleteSpace } from '@/lib/api';
import type { Space, FocusMode } from '@/lib/types'; import type { Space } from '@/lib/types';
import { useAuth } from '@/lib/contexts/AuthContext';
const focusModes: { value: FocusMode; label: string; icon: React.ElementType }[] = [ const spaceColors = [
{ value: 'all', label: 'Все источники', icon: Globe }, 'from-violet-500/20 to-purple-500/20 border-violet-500/30',
{ value: 'academic', label: 'Академический', icon: BookOpen }, 'from-blue-500/20 to-cyan-500/20 border-blue-500/30',
{ value: 'code', label: 'Код', icon: Code2 }, 'from-emerald-500/20 to-teal-500/20 border-emerald-500/30',
{ value: 'news', label: 'Новости', icon: Newspaper }, 'from-orange-500/20 to-amber-500/20 border-orange-500/30',
{ value: 'finance', label: 'Финансы', icon: TrendingUp }, 'from-pink-500/20 to-rose-500/20 border-pink-500/30',
{ value: 'youtube', label: 'YouTube', icon: Youtube }, 'from-indigo-500/20 to-blue-500/20 border-indigo-500/30',
]; ];
function getSpaceColor(index: number): string {
return spaceColors[index % spaceColors.length];
}
export default function SpacesPage() { export default function SpacesPage() {
const router = useRouter(); const router = useRouter();
const { user, isAuthenticated, showAuthModal } = useAuth();
const [spaces, setSpaces] = useState<Space[]>([]); const [spaces, setSpaces] = useState<Space[]>([]);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [search, setSearch] = useState(''); const [search, setSearch] = useState('');
const load = useCallback(async () => { const load = useCallback(async () => {
if (!isAuthenticated) {
setIsLoading(false);
return;
}
setIsLoading(true); setIsLoading(true);
try { try {
const data = await fetchSpaces(); const data = await fetchSpaces();
@@ -35,14 +58,15 @@ export default function SpacesPage() {
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
}, []); }, [isAuthenticated]);
useEffect(() => { useEffect(() => {
load(); load();
}, [load]); }, [load]);
const handleDelete = async (id: string) => { const handleDelete = async (e: React.MouseEvent, id: string) => {
if (!confirm('Удалить пространство? Все связанные треды останутся в истории.')) return; e.stopPropagation();
if (!confirm('Удалить пространство? Все связанные треды будут удалены.')) return;
try { try {
await deleteSpace(id); await deleteSpace(id);
@@ -60,91 +84,96 @@ export default function SpacesPage() {
); );
}, [spaces, search]); }, [spaces, search]);
const openSpace = (id: string) => { if (!isAuthenticated) {
router.push(`/?space=${id}`); return (
}; <div className="h-full overflow-y-auto">
<div className="flex flex-col items-center justify-center min-h-[60vh] px-4">
const getFocusModeIcon = (mode: FocusMode) => { <div className="w-16 h-16 rounded-2xl bg-gradient-to-br from-accent/20 to-accent/5 flex items-center justify-center mb-6">
const found = focusModes.find((m) => m.value === mode); <FolderOpen className="w-8 h-8 text-accent" />
return found?.icon || Globe; </div>
}; <h1 className="text-2xl font-semibold text-primary mb-2">Пространства</h1>
<p className="text-secondary text-center max-w-md mb-6">
Создавайте пространства для организации исследований и совместной работы с командой
</p>
<button
onClick={() => showAuthModal('login')}
className="btn-gradient px-6 py-3"
>
<span className="btn-gradient-text">Войти для доступа</span>
</button>
</div>
</div>
);
}
return ( return (
<div className="h-full overflow-y-auto"> <div className="h-full overflow-y-auto">
<div className="max-w-2xl mx-auto px-4 sm:px-6 py-6 sm:py-8"> <div className="max-w-5xl mx-auto px-4 sm:px-6 py-6 sm:py-8">
{/* Header */} {/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6 sm:mb-8"> <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-8">
<div> <div>
<h1 className="text-xl sm:text-2xl font-semibold text-primary mb-1 sm:mb-2">Пространства</h1> <h1 className="text-2xl sm:text-3xl font-bold text-primary mb-1">Пространства</h1>
<p className="text-sm text-secondary">Организуйте исследования по темам</p> <p className="text-secondary">Организуйте исследования и работайте вместе с командой</p>
</div> </div>
<div className="flex items-center gap-2">
<button
onClick={load}
disabled={isLoading}
className="flex items-center gap-2 px-3 py-2.5 text-sm text-secondary hover:text-primary bg-surface/40 border border-border/50 hover-gradient rounded-xl transition-all"
>
<RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
</button>
<Link <Link
href="/spaces/new" href="/spaces/new"
className="flex items-center gap-2 px-4 py-2.5 text-sm btn-gradient" className="flex items-center gap-2 px-5 py-2.5 btn-gradient"
> >
<Plus className="w-4 h-4 btn-gradient-text" /> <Plus className="w-4 h-4 btn-gradient-text" />
<span className="hidden sm:inline btn-gradient-text">Создать</span> <span className="btn-gradient-text font-medium">Создать</span>
</Link> </Link>
</div> </div>
</div>
{/* Search */} {/* Search */}
<div className="relative mb-6"> <div className="relative mb-8">
<Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-muted" /> <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-muted" />
<input <input
value={search} value={search}
onChange={(e) => setSearch(e.target.value)} onChange={(e) => setSearch(e.target.value)}
placeholder="Поиск пространств..." placeholder="Поиск пространств..."
className="w-full pl-11 pr-4 py-3 text-sm bg-elevated/40 border border-border/50 rounded-xl text-primary placeholder:text-muted focus:outline-none input-gradient transition-colors" className="w-full pl-12 pr-4 py-3.5 text-sm bg-elevated/40 border border-border/50 rounded-xl text-primary placeholder:text-muted focus:outline-none input-gradient transition-colors"
/> />
</div> </div>
{/* Content */} {/* Content */}
{isLoading ? ( {isLoading ? (
<div className="flex flex-col items-center justify-center py-16 sm:py-20"> <div className="flex flex-col items-center justify-center py-20">
<Loader2 className="w-8 h-8 animate-spin loader-gradient" /> <Loader2 className="w-8 h-8 animate-spin loader-gradient" />
<p className="text-sm text-muted mt-4">Загрузка пространств...</p> <p className="text-sm text-muted mt-4">Загрузка пространств...</p>
</div> </div>
) : filtered.length > 0 ? ( ) : filtered.length > 0 ? (
<div className="grid gap-3"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{filtered.map((space, i) => { {filtered.map((space, i) => (
const FocusIcon = getFocusModeIcon(space.focusMode || 'all');
return (
<motion.div <motion.div
key={space.id} key={space.id}
initial={{ opacity: 0, y: 8 }} initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
transition={{ delay: i * 0.05 }} transition={{ delay: i * 0.05 }}
onClick={() => openSpace(space.id)}
className="group flex items-center gap-3 sm:gap-4 p-3 sm:p-4 bg-elevated/40 border border-border/40 rounded-xl hover:bg-elevated/60 hover-gradient cursor-pointer transition-all duration-200"
> >
<div className="w-10 h-10 sm:w-12 sm:h-12 rounded-xl icon-gradient flex items-center justify-center flex-shrink-0"> <Link
<FolderOpen className="w-4 h-4 sm:w-5 sm:h-5 text-gradient" /> href={`/spaces/${space.id}`}
</div> className={`
<div className="flex-1 min-w-0"> group block p-5 rounded-2xl border bg-gradient-to-br
<h3 className="text-sm font-medium text-primary group-hover:text-gradient transition-colors truncate"> ${getSpaceColor(i)}
{space.name} hover:scale-[1.02] transition-all duration-200
</h3> `}
<div className="flex items-center gap-2 mt-1"> >
<FocusIcon className="w-3 h-3 text-muted flex-shrink-0" /> {/* Header */}
<span className="text-xs text-muted truncate"> <div className="flex items-start justify-between mb-4">
{space.description || focusModes.find((m) => m.value === space.focusMode)?.label || 'Все источники'} <div className="w-12 h-12 rounded-xl bg-white/10 backdrop-blur-sm flex items-center justify-center">
</span> <FolderOpen className="w-6 h-6 text-primary" />
</div>
</div> </div>
<div className="flex items-center gap-1">
{space.isPublic ? (
<Globe className="w-4 h-4 text-muted" />
) : (
<Lock className="w-4 h-4 text-muted" />
)}
<DropdownMenu.Root> <DropdownMenu.Root>
<DropdownMenu.Trigger asChild> <DropdownMenu.Trigger asChild>
<button <button
onClick={(e) => e.stopPropagation()} onClick={(e) => e.preventDefault()}
className="p-2 hover:bg-surface/60 rounded-lg transition-all sm:opacity-0 sm:group-hover:opacity-100" className="p-1.5 hover:bg-white/10 rounded-lg transition-colors opacity-0 group-hover:opacity-100"
> >
<MoreHorizontal className="w-4 h-4 text-secondary" /> <MoreHorizontal className="w-4 h-4 text-secondary" />
</button> </button>
@@ -157,46 +186,102 @@ export default function SpacesPage() {
<DropdownMenu.Item asChild> <DropdownMenu.Item asChild>
<Link <Link
href={`/spaces/${space.id}/edit`} href={`/spaces/${space.id}/edit`}
onClick={(e) => e.stopPropagation()}
className="flex items-center gap-2 px-3 py-2.5 text-sm text-secondary rounded-lg cursor-pointer hover:bg-elevated/80 hover:text-primary outline-none transition-colors" className="flex items-center gap-2 px-3 py-2.5 text-sm text-secondary rounded-lg cursor-pointer hover:bg-elevated/80 hover:text-primary outline-none transition-colors"
> >
<Settings className="w-4 h-4" /> <Settings className="w-4 h-4" />
Редактировать Настройки
</Link> </Link>
</DropdownMenu.Item> </DropdownMenu.Item>
{space.userId === user?.id && (
<DropdownMenu.Item <DropdownMenu.Item
onClick={(e) => { onClick={(e) => handleDelete(e as unknown as React.MouseEvent, space.id)}
e.stopPropagation();
handleDelete(space.id);
}}
className="flex items-center gap-2 px-3 py-2.5 text-sm text-error rounded-lg cursor-pointer hover:bg-error/10 outline-none transition-colors" className="flex items-center gap-2 px-3 py-2.5 text-sm text-error rounded-lg cursor-pointer hover:bg-error/10 outline-none transition-colors"
> >
<Trash2 className="w-4 h-4" /> <Trash2 className="w-4 h-4" />
Удалить Удалить
</DropdownMenu.Item> </DropdownMenu.Item>
)}
</DropdownMenu.Content> </DropdownMenu.Content>
</DropdownMenu.Portal> </DropdownMenu.Portal>
</DropdownMenu.Root> </DropdownMenu.Root>
</div>
</div>
{/* Title & Description */}
<h3 className="text-lg font-semibold text-primary mb-1 group-hover:text-gradient transition-colors">
{space.name}
</h3>
<p className="text-sm text-secondary line-clamp-2 mb-4 min-h-[40px]">
{space.description || 'Без описания'}
</p>
{/* Stats */}
<div className="flex items-center gap-4 text-xs text-muted">
<div className="flex items-center gap-1.5">
<Users className="w-3.5 h-3.5" />
<span>{space.memberCount || 1}</span>
</div>
<div className="flex items-center gap-1.5">
<MessageSquare className="w-3.5 h-3.5" />
<span>{space.threadCount || 0} тредов</span>
</div>
</div>
{/* Members avatars */}
{space.members && space.members.length > 0 && (
<div className="flex items-center gap-1 mt-4 pt-4 border-t border-white/10">
<div className="flex -space-x-2">
{space.members.slice(0, 4).map((member, idx) => (
<div
key={member.id}
className="w-7 h-7 rounded-full bg-surface border-2 border-base flex items-center justify-center"
title={member.name || member.email}
>
{member.avatar ? (
<img src={member.avatar} alt="" className="w-full h-full rounded-full object-cover" />
) : (
<span className="text-[10px] font-medium text-secondary">
{(member.name || member.email || '?').charAt(0).toUpperCase()}
</span>
)}
</div>
))}
{(space.memberCount || 0) > 4 && (
<div className="w-7 h-7 rounded-full bg-surface border-2 border-base flex items-center justify-center">
<span className="text-[10px] font-medium text-muted">
+{(space.memberCount || 0) - 4}
</span>
</div>
)}
</div>
</div>
)}
</Link>
</motion.div> </motion.div>
); ))}
})}
</div> </div>
) : ( ) : (
<div className="text-center py-16 sm:py-20"> <div className="text-center py-20">
<FolderOpen className="w-12 h-12 mx-auto mb-4 text-muted" /> <div className="w-20 h-20 rounded-2xl bg-gradient-to-br from-accent/20 to-accent/5 flex items-center justify-center mx-auto mb-6">
<p className="text-secondary mb-1"> <FolderOpen className="w-10 h-10 text-accent" />
</div>
<h2 className="text-xl font-semibold text-primary mb-2">
{search ? 'Ничего не найдено' : 'Нет пространств'} {search ? 'Ничего не найдено' : 'Нет пространств'}
</h2>
<p className="text-secondary mb-8 max-w-md mx-auto">
{search
? 'Попробуйте изменить поисковый запрос'
: 'Создайте первое пространство для организации ваших исследований и совместной работы'}
</p> </p>
<p className="text-sm text-muted mb-6"> {!search && (
Создайте пространство для организации исследований
</p>
<Link <Link
href="/spaces/new" href="/spaces/new"
className="inline-flex items-center gap-2 px-4 py-2.5 text-sm btn-gradient" className="inline-flex items-center gap-2 px-6 py-3 btn-gradient"
> >
<Plus className="w-4 h-4 btn-gradient-text" /> <Plus className="w-5 h-5 btn-gradient-text" />
<span className="btn-gradient-text">Создать пространство</span> <span className="btn-gradient-text font-medium">Создать пространство</span>
</Link> </Link>
)}
</div> </div>
)} )}
</div> </div>

View File

@@ -16,10 +16,13 @@ import {
X, X,
FileText, FileText,
File, File,
Bot,
Cpu,
} from 'lucide-react'; } from 'lucide-react';
import * as DropdownMenu from '@radix-ui/react-dropdown-menu'; import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
type Mode = 'speed' | 'balanced' | 'quality'; type Mode = 'speed' | 'balanced' | 'quality';
type ModelID = 'auto' | 'gooseek-1.0';
export interface ChatAttachment { export interface ChatAttachment {
id: string; id: string;
@@ -28,10 +31,16 @@ export interface ChatAttachment {
preview?: string; preview?: string;
} }
export interface ChatModel {
providerId: string;
key: string;
}
export interface SendOptions { export interface SendOptions {
mode: Mode; mode: Mode;
webSearch: boolean; webSearch: boolean;
attachments: ChatAttachment[]; attachments: ChatAttachment[];
model: ChatModel;
} }
interface ChatInputProps { interface ChatInputProps {
@@ -50,9 +59,15 @@ const modes: { value: Mode; label: string; icon: typeof Zap; desc: string }[] =
{ value: 'quality', label: 'Качество', icon: Sparkles, desc: '~60 сек' }, { value: 'quality', label: 'Качество', icon: Sparkles, desc: '~60 сек' },
]; ];
const models: { id: ModelID; label: string; icon: typeof Bot; desc: string; providerId: string; key: string }[] = [
{ id: 'auto', label: 'Auto', icon: Cpu, desc: 'Бесплатно', providerId: 'ollama', key: '' },
{ id: 'gooseek-1.0', label: 'GooSeek 1.0', icon: Bot, desc: 'По тарифу', providerId: 'timeweb', key: 'gpt-4o' },
];
export function ChatInput({ onSend, onStop, isLoading, placeholder, autoFocus, value: externalValue, onChange: externalOnChange }: ChatInputProps) { export function ChatInput({ onSend, onStop, isLoading, placeholder, autoFocus, value: externalValue, onChange: externalOnChange }: ChatInputProps) {
const [internalMessage, setInternalMessage] = useState(''); const [internalMessage, setInternalMessage] = useState('');
const [mode, setMode] = useState<Mode>('balanced'); const [mode, setMode] = useState<Mode>('balanced');
const [modelId, setModelId] = useState<ModelID>('auto');
const [isFocused, setIsFocused] = useState(false); const [isFocused, setIsFocused] = useState(false);
const [webSearchEnabled, setWebSearchEnabled] = useState(false); const [webSearchEnabled, setWebSearchEnabled] = useState(false);
const [attachments, setAttachments] = useState<ChatAttachment[]>([]); const [attachments, setAttachments] = useState<ChatAttachment[]>([]);
@@ -73,10 +88,15 @@ export function ChatInput({ onSend, onStop, isLoading, placeholder, autoFocus, v
const handleSubmit = useCallback(() => { const handleSubmit = useCallback(() => {
if ((message.trim() || attachments.length > 0) && !isLoading) { if ((message.trim() || attachments.length > 0) && !isLoading) {
const selectedModel = models.find(m => m.id === modelId) || models[0];
onSend(message.trim(), { onSend(message.trim(), {
mode, mode,
webSearch: webSearchEnabled, webSearch: webSearchEnabled,
attachments, attachments,
model: {
providerId: selectedModel.providerId,
key: selectedModel.key,
},
}); });
if (isControlled && externalOnChange) { if (isControlled && externalOnChange) {
externalOnChange(''); externalOnChange('');
@@ -88,7 +108,7 @@ export function ChatInput({ onSend, onStop, isLoading, placeholder, autoFocus, v
textareaRef.current.style.height = 'auto'; textareaRef.current.style.height = 'auto';
} }
} }
}, [message, mode, webSearchEnabled, attachments, isLoading, onSend, isControlled, externalOnChange]); }, [message, mode, modelId, webSearchEnabled, attachments, isLoading, onSend, isControlled, externalOnChange]);
const handleFileSelect = useCallback((e: ChangeEvent<HTMLInputElement>, type: 'file' | 'image') => { const handleFileSelect = useCallback((e: ChangeEvent<HTMLInputElement>, type: 'file' | 'image') => {
const files = e.target.files; const files = e.target.files;
@@ -142,6 +162,7 @@ export function ChatInput({ onSend, onStop, isLoading, placeholder, autoFocus, v
}; };
const currentMode = modes.find((m) => m.value === mode)!; const currentMode = modes.find((m) => m.value === mode)!;
const currentModel = models.find((m) => m.id === modelId) || models[0];
return ( return (
<div className="relative w-full"> <div className="relative w-full">
@@ -162,32 +183,32 @@ export function ChatInput({ onSend, onStop, isLoading, placeholder, autoFocus, v
{attachments.map((attachment) => ( {attachments.map((attachment) => (
<div <div
key={attachment.id} key={attachment.id}
className="relative group flex items-center gap-2 bg-surface/80 border border-border/50 rounded-lg px-3 py-2" className="relative group flex items-center gap-1.5 bg-surface/80 border border-border/50 rounded-lg px-2 py-1"
> >
{attachment.type === 'image' && attachment.preview ? ( {attachment.type === 'image' && attachment.preview ? (
<img <img
src={attachment.preview} src={attachment.preview}
alt={attachment.file.name} alt={attachment.file.name}
className="w-8 h-8 object-cover rounded" className="w-6 h-6 object-cover rounded"
/> />
) : ( ) : (
<div className="w-8 h-8 flex items-center justify-center bg-accent/10 rounded"> <div className="w-6 h-6 flex items-center justify-center bg-accent/10 rounded">
{attachment.file.type.includes('pdf') ? ( {attachment.file.type.includes('pdf') ? (
<FileText className="w-4 h-4 text-accent" /> <FileText className="w-3.5 h-3.5 text-accent" />
) : ( ) : (
<File className="w-4 h-4 text-accent" /> <File className="w-3.5 h-3.5 text-accent" />
)} )}
</div> </div>
)} )}
<span className="text-xs text-secondary max-w-[120px] truncate"> <span className="text-xs text-secondary max-w-[140px] truncate">
{attachment.file.name} {attachment.file.name}
</span> </span>
<button <button
onClick={() => removeAttachment(attachment.id)} onClick={() => removeAttachment(attachment.id)}
className="ml-1 p-0.5 rounded-full hover:bg-error/20 text-muted hover:text-error transition-colors" className="p-0.5 rounded-full hover:bg-error/20 text-muted hover:text-error transition-colors"
title="Удалить" title="Удалить"
> >
<X className="w-3.5 h-3.5" /> <X className="w-3 h-3" />
</button> </button>
</div> </div>
))} ))}
@@ -227,12 +248,12 @@ export function ChatInput({ onSend, onStop, isLoading, placeholder, autoFocus, v
className={` className={`
w-10 h-10 flex items-center justify-center rounded-xl transition-all duration-200 w-10 h-10 flex items-center justify-center rounded-xl transition-all duration-200
${(message.trim() || attachments.length > 0) ${(message.trim() || attachments.length > 0)
? 'btn-gradient' ? 'btn-gradient text-accent'
: 'bg-surface/50 text-muted border border-border/50' : 'bg-surface/50 text-muted border border-border/50'
} }
`} `}
> >
<ArrowUp className={`w-5 h-5 ${(message.trim() || attachments.length > 0) ? 'btn-gradient-text' : ''}`} /> <ArrowUp className="w-5 h-5 flex-shrink-0" />
</button> </button>
)} )}
</div> </div>
@@ -276,6 +297,41 @@ export function ChatInput({ onSend, onStop, isLoading, placeholder, autoFocus, v
</DropdownMenu.Portal> </DropdownMenu.Portal>
</DropdownMenu.Root> </DropdownMenu.Root>
{/* Model Selector */}
<DropdownMenu.Root>
<DropdownMenu.Trigger asChild>
<button className="flex items-center gap-2 h-8 px-3 text-xs text-secondary hover:text-primary rounded-lg hover:bg-surface/50 transition-all">
<currentModel.icon className="w-4 h-4 text-gradient" />
<span className="font-medium">{currentModel.label}</span>
<ChevronDown className="w-3.5 h-3.5 opacity-50" />
</button>
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content
className="min-w-[180px] bg-surface/95 backdrop-blur-xl border border-border rounded-xl p-1.5 shadow-dropdown z-50"
sideOffset={8}
>
{models.map((m) => (
<DropdownMenu.Item
key={m.id}
onClick={() => setModelId(m.id)}
className={`
flex items-center gap-3 px-3 py-2.5 text-sm rounded-lg cursor-pointer outline-none transition-colors
${modelId === m.id
? 'active-gradient text-primary'
: 'text-secondary hover:bg-elevated/80 hover:text-primary'
}
`}
>
<m.icon className={`w-4 h-4 ${modelId === m.id ? 'text-gradient' : 'text-muted'}`} />
<span className={`flex-1 font-medium ${modelId === m.id ? 'text-gradient' : ''}`}>{m.label}</span>
<span className={`text-xs ${m.id === 'auto' ? 'text-success' : 'text-muted'}`}>{m.desc}</span>
</DropdownMenu.Item>
))}
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
{/* Separator */} {/* Separator */}
<div className="w-px h-5 bg-border/50 mx-1" /> <div className="w-px h-5 bg-border/50 mx-1" />
@@ -324,11 +380,6 @@ export function ChatInput({ onSend, onStop, isLoading, placeholder, autoFocus, v
/> />
</div> </div>
<div className="flex items-center gap-3">
<span className="text-xs text-faint">
Enter для отправки · Shift+Enter для новой строки
</span>
</div>
</div> </div>
</motion.div> </motion.div>

View File

@@ -9,7 +9,6 @@ import {
Compass, Compass,
FolderOpen, FolderOpen,
Clock, Clock,
Settings,
ChevronLeft, ChevronLeft,
ChevronRight, ChevronRight,
TrendingUp, TrendingUp,
@@ -19,7 +18,8 @@ import {
X, X,
Shield, Shield,
LogIn, LogIn,
UserPlus, Wallet,
ChevronRight as ChevronRightIcon,
} from 'lucide-react'; } from 'lucide-react';
import { filterMenuItems } from '@/lib/config/menu'; import { filterMenuItems } from '@/lib/config/menu';
import { useAuth } from '@/lib/contexts/AuthContext'; import { useAuth } from '@/lib/contexts/AuthContext';
@@ -65,12 +65,12 @@ export function Sidebar({ onClose }: SidebarProps) {
return ( return (
<motion.aside <motion.aside
initial={false} initial={false}
animate={{ width: isMobile ? 280 : collapsed ? 68 : 260 }} animate={{ width: isMobile ? 240 : collapsed ? 56 : 200 }}
transition={{ duration: 0.2, ease: [0.4, 0, 0.2, 1] }} transition={{ duration: 0.2, ease: [0.4, 0, 0.2, 1] }}
className="h-full flex flex-col bg-base border-r border-border/50" className="h-full flex flex-col bg-base border-r border-border/50"
> >
{/* Header */} {/* Header */}
<div className="h-16 px-4 flex items-center justify-between"> <div className="h-12 px-3 flex items-center justify-between">
<AnimatePresence mode="wait"> <AnimatePresence mode="wait">
{(isMobile || !collapsed) && ( {(isMobile || !collapsed) && (
<motion.div <motion.div
@@ -79,7 +79,7 @@ export function Sidebar({ onClose }: SidebarProps) {
exit={{ opacity: 0 }} exit={{ opacity: 0 }}
transition={{ duration: 0.15 }} transition={{ duration: 0.15 }}
> >
<span className="font-black italic text-primary tracking-tight text-3xl">GooSeek</span> <span className="font-black italic text-primary tracking-tight text-xl">GooSeek</span>
</motion.div> </motion.div>
)} )}
</AnimatePresence> </AnimatePresence>
@@ -87,26 +87,26 @@ export function Sidebar({ onClose }: SidebarProps) {
{isMobile ? ( {isMobile ? (
<button <button
onClick={onClose} onClick={onClose}
className="w-9 h-9 flex items-center justify-center rounded-xl text-muted hover:text-primary hover:bg-surface/50 transition-all" className="w-7 h-7 flex items-center justify-center rounded-lg text-muted hover:text-primary hover:bg-surface/50 transition-all"
> >
<X className="w-5 h-5" /> <X className="w-4 h-4" />
</button> </button>
) : ( ) : (
<button <button
onClick={toggleCollapse} onClick={toggleCollapse}
className="w-8 h-8 flex items-center justify-center rounded-lg text-muted hover:text-secondary hover:bg-surface/50 transition-all" className="w-6 h-6 flex items-center justify-center rounded text-muted hover:text-secondary hover:bg-surface/50 transition-all"
> >
{collapsed ? ( {collapsed ? (
<ChevronRight className="w-4 h-4" /> <ChevronRight className="w-3.5 h-3.5" />
) : ( ) : (
<ChevronLeft className="w-4 h-4" /> <ChevronLeft className="w-3.5 h-3.5" />
)} )}
</button> </button>
)} )}
</div> </div>
{/* Navigation */} {/* Navigation */}
<nav className="flex-1 px-3 py-4 space-y-1 overflow-y-auto"> <nav className="flex-1 px-2 py-2 space-y-0.5 overflow-y-auto">
{navItems.map((item) => ( {navItems.map((item) => (
<NavLink <NavLink
key={item.href} key={item.href}
@@ -120,13 +120,13 @@ export function Sidebar({ onClose }: SidebarProps) {
))} ))}
{/* Tools Section */} {/* Tools Section */}
<div className="pt-6 pb-2"> <div className="pt-4 pb-1">
{(isMobile || !collapsed) && ( {(isMobile || !collapsed) && (
<span className="px-3 text-[11px] font-semibold text-muted uppercase tracking-wider"> <span className="px-2 text-[10px] font-semibold text-muted uppercase tracking-wider">
Инструменты Инструменты
</span> </span>
)} )}
{!isMobile && collapsed && <div className="h-px bg-border/30 mx-2" />} {!isMobile && collapsed && <div className="h-px bg-border/30 mx-1" />}
</div> </div>
{toolItems.map((item) => ( {toolItems.map((item) => (
@@ -142,8 +142,8 @@ export function Sidebar({ onClose }: SidebarProps) {
))} ))}
</nav> </nav>
{/* Footer */} {/* Footer - Profile Block */}
<div className="p-3 border-t border-border/30 space-y-1"> <div className="p-2 border-t border-border/30">
{isAdmin && ( {isAdmin && (
<NavLink <NavLink
href="/admin" href="/admin"
@@ -154,83 +154,86 @@ export function Sidebar({ onClose }: SidebarProps) {
onClick={handleNavClick} onClick={handleNavClick}
/> />
)} )}
<NavLink
href="/settings"
icon={Settings}
label="Настройки"
collapsed={!isMobile && collapsed}
active={pathname === '/settings'}
onClick={handleNavClick}
/>
{/* Auth buttons for non-authenticated users */} {/* Guest - Login button */}
{!isAuthenticated && ( {!isAuthenticated && (
<div className={`pt-2 ${collapsed && !isMobile ? 'px-0' : ''}`}> <div className={`${isAdmin ? 'mt-1' : ''}`}>
{collapsed && !isMobile ? ( {collapsed && !isMobile ? (
<button <button
onClick={() => showAuthModal('login')} onClick={() => showAuthModal('login')}
className="w-full h-10 flex items-center justify-center rounded-xl bg-accent/10 text-accent hover:bg-accent/20 transition-all" className="btn-gradient w-full h-9 flex items-center justify-center"
> >
<LogIn className="w-[18px] h-[18px]" /> <LogIn className="w-4 h-4 btn-gradient-text" />
</button> </button>
) : ( ) : (
<div className="space-y-2">
<button <button
onClick={() => { showAuthModal('login'); handleNavClick(); }} onClick={() => { showAuthModal('login'); handleNavClick(); }}
className="w-full h-10 flex items-center justify-center gap-2 rounded-xl bg-surface/50 text-secondary hover:text-primary hover:bg-surface transition-all text-sm font-medium" className="btn-gradient w-full h-9 flex items-center justify-center gap-2"
> >
<LogIn className="w-4 h-4" /> <LogIn className="w-3.5 h-3.5 btn-gradient-text" />
Войти <span className="btn-gradient-text text-xs font-medium">Войти</span>
</button> </button>
<button
onClick={() => { showAuthModal('register'); handleNavClick(); }}
className="w-full h-10 flex items-center justify-center gap-2 rounded-xl bg-accent text-white hover:bg-accent-hover transition-all text-sm font-medium"
>
<UserPlus className="w-4 h-4" />
Регистрация
</button>
</div>
)} )}
</div> </div>
)} )}
{/* User info for authenticated users */} {/* Authenticated - Profile with balance */}
{isAuthenticated && user && ( {isAuthenticated && user && (
<div className={`pt-2 ${collapsed && !isMobile ? 'justify-center' : ''}`}> <div className={`${isAdmin ? 'mt-1' : ''}`}>
{collapsed && !isMobile ? ( {collapsed && !isMobile ? (
<Link <Link
href="/settings" href="/settings"
className="w-full h-10 flex items-center justify-center rounded-xl hover:bg-surface/50 transition-all" onClick={handleNavClick}
className="w-full flex flex-col items-center gap-1"
> >
<div className="w-8 h-8 rounded-full bg-accent/20 flex items-center justify-center"> <div className="w-8 h-8 rounded-full bg-accent/20 flex items-center justify-center hover:bg-accent/30 transition-all">
{user.avatar ? ( {user.avatar ? (
<img src={user.avatar} alt={user.name} className="w-full h-full rounded-full object-cover" /> <img src={user.avatar} alt={user.name} className="w-full h-full rounded-full object-cover" />
) : ( ) : (
<span className="text-sm font-medium text-accent"> <span className="text-xs font-semibold text-accent">
{user.name.charAt(0).toUpperCase()} {user.name.charAt(0).toUpperCase()}
</span> </span>
)} )}
</div> </div>
<div className="flex items-center gap-0.5 px-1.5 py-0.5 rounded bg-surface/50">
<Wallet className="w-2.5 h-2.5 text-accent" />
<span className="text-[10px] font-medium text-primary">{user.balance ?? 0}</span>
</div>
</Link> </Link>
) : ( ) : (
<Link <Link
href="/settings" href="/settings"
onClick={handleNavClick} onClick={handleNavClick}
className="flex items-center gap-3 px-3 py-2 rounded-xl hover:bg-surface/50 transition-all" className="flex items-center gap-2 p-1.5 rounded-lg bg-surface/30 hover:bg-surface/50 border border-border/30 hover:border-border/50 transition-all group"
> >
<div className="w-8 h-8 rounded-full bg-accent/20 flex items-center justify-center flex-shrink-0"> <div className="w-8 h-8 rounded-full bg-accent/20 flex items-center justify-center flex-shrink-0">
{user.avatar ? ( {user.avatar ? (
<img src={user.avatar} alt={user.name} className="w-full h-full rounded-full object-cover" /> <img src={user.avatar} alt={user.name} className="w-full h-full rounded-full object-cover" />
) : ( ) : (
<span className="text-sm font-medium text-accent"> <span className="text-xs font-semibold text-accent">
{user.name.charAt(0).toUpperCase()} {user.name.charAt(0).toUpperCase()}
</span> </span>
)} )}
</div> </div>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<div className="text-sm font-medium text-primary truncate">{user.name}</div> <div className="flex items-center gap-1">
<div className="text-xs text-muted truncate">{user.email}</div> <span className="text-xs font-medium text-primary truncate">{user.name}</span>
<span className={`text-[9px] font-medium px-1 py-0.5 rounded ${
user.tier === 'business'
? 'bg-amber-500/20 text-amber-400'
: user.tier === 'pro'
? 'bg-accent/20 text-accent'
: 'bg-surface text-muted'
}`}>
{user.tier === 'business' ? 'Biz' : user.tier === 'pro' ? 'Pro' : 'Free'}
</span>
</div> </div>
<div className="flex items-center gap-1 mt-0.5">
<Wallet className="w-2.5 h-2.5 text-accent" />
<span className="text-[10px] font-medium text-secondary">{(user.balance ?? 0).toLocaleString('ru-RU')} </span>
</div>
</div>
<ChevronRightIcon className="w-3.5 h-3.5 text-muted group-hover:text-secondary transition-colors" />
</Link> </Link>
)} )}
</div> </div>
@@ -255,17 +258,17 @@ function NavLink({ href, icon: Icon, label, collapsed, active, onClick }: NavLin
href={href} href={href}
onClick={onClick} onClick={onClick}
className={` className={`
flex items-center gap-3 h-11 rounded-xl transition-all duration-150 flex items-center gap-2 h-9 rounded-lg transition-all duration-150
${collapsed ? 'justify-center px-0' : 'px-3'} ${collapsed ? 'justify-center px-0' : 'px-2'}
${active ${active
? 'active-gradient text-primary border-l-gradient ml-0' ? 'active-gradient text-primary border-l-gradient ml-0'
: 'text-secondary hover:text-primary hover:bg-surface/50' : 'text-secondary hover:text-primary hover:bg-surface/50'
} }
`} `}
> >
<Icon className={`w-[18px] h-[18px] flex-shrink-0 ${active ? 'text-gradient' : ''}`} /> <Icon className={`w-4 h-4 flex-shrink-0 ${active ? 'text-gradient' : ''}`} />
{!collapsed && ( {!collapsed && (
<span className={`text-sm font-medium truncate ${active ? 'text-gradient' : ''}`}>{label}</span> <span className={`text-xs font-medium truncate ${active ? 'text-gradient' : ''}`}>{label}</span>
)} )}
</Link> </Link>
); );

View File

@@ -0,0 +1,320 @@
'use client';
import { useState } from 'react';
import { motion } from 'framer-motion';
import { User, Mail, Key, LogOut, Trash2, Camera, Check, X, Loader2 } from 'lucide-react';
import { useAuth } from '@/lib/contexts/AuthContext';
import { updateProfile, changePassword, logoutAll, UpdateProfileRequest, ChangePasswordRequest } from '@/lib/auth';
export function AccountTab() {
const { user, logout, refreshUser } = useAuth();
const [isEditingProfile, setIsEditingProfile] = useState(false);
const [isChangingPassword, setIsChangingPassword] = useState(false);
const [profileForm, setProfileForm] = useState({ name: user?.name || '' });
const [passwordForm, setPasswordForm] = useState({ currentPassword: '', newPassword: '', confirmPassword: '' });
const [loading, setLoading] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const handleProfileSave = async () => {
if (!profileForm.name.trim()) {
setError('Имя не может быть пустым');
return;
}
setLoading('profile');
setError(null);
try {
await updateProfile({ name: profileForm.name } as UpdateProfileRequest);
await refreshUser();
setIsEditingProfile(false);
setSuccess('Профиль обновлён');
setTimeout(() => setSuccess(null), 3000);
} catch (err) {
setError(err instanceof Error ? err.message : 'Ошибка обновления профиля');
} finally {
setLoading(null);
}
};
const handlePasswordChange = async () => {
if (passwordForm.newPassword !== passwordForm.confirmPassword) {
setError('Пароли не совпадают');
return;
}
if (passwordForm.newPassword.length < 8) {
setError('Пароль должен быть минимум 8 символов');
return;
}
setLoading('password');
setError(null);
try {
await changePassword({
currentPassword: passwordForm.currentPassword,
newPassword: passwordForm.newPassword,
} as ChangePasswordRequest);
setIsChangingPassword(false);
setPasswordForm({ currentPassword: '', newPassword: '', confirmPassword: '' });
setSuccess('Пароль изменён');
setTimeout(() => setSuccess(null), 3000);
} catch (err) {
setError(err instanceof Error ? err.message : 'Ошибка смены пароля');
} finally {
setLoading(null);
}
};
const handleLogoutAll = async () => {
setLoading('logoutAll');
try {
await logoutAll();
window.location.href = '/';
} catch {
setError('Ошибка выхода');
} finally {
setLoading(null);
}
};
const handleLogout = async () => {
setLoading('logout');
try {
await logout();
window.location.href = '/';
} catch {
setError('Ошибка выхода');
} finally {
setLoading(null);
}
};
if (!user) return null;
return (
<div className="space-y-6">
{error && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
className="p-3 bg-error/10 border border-error/20 rounded-xl text-error text-sm"
>
{error}
</motion.div>
)}
{success && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
className="p-3 bg-success/10 border border-success/20 rounded-xl text-success text-sm"
>
{success}
</motion.div>
)}
{/* Profile Section */}
<Section title="Профиль" icon={User}>
<div className="p-4 bg-elevated/40 border border-border/40 rounded-xl">
<div className="flex items-start gap-4">
<div className="relative">
<div className="w-16 h-16 rounded-full bg-accent/20 flex items-center justify-center">
{user.avatar ? (
<img src={user.avatar} alt={user.name} className="w-full h-full rounded-full object-cover" />
) : (
<span className="text-2xl font-semibold text-accent">
{user.name.charAt(0).toUpperCase()}
</span>
)}
</div>
<button className="absolute -bottom-1 -right-1 w-7 h-7 rounded-full bg-surface border border-border flex items-center justify-center hover:bg-surface/80 transition-all">
<Camera className="w-3.5 h-3.5 text-muted" />
</button>
</div>
<div className="flex-1 min-w-0">
{isEditingProfile ? (
<div className="space-y-3">
<input
type="text"
value={profileForm.name}
onChange={(e) => setProfileForm({ ...profileForm, name: e.target.value })}
className="w-full px-3 py-2 bg-surface border border-border rounded-lg text-sm text-primary focus:outline-none focus:border-accent"
placeholder="Ваше имя"
/>
<div className="flex gap-2">
<button
onClick={handleProfileSave}
disabled={loading === 'profile'}
className="flex items-center gap-1.5 px-3 py-1.5 bg-accent text-white rounded-lg text-sm hover:bg-accent-hover transition-all disabled:opacity-50"
>
{loading === 'profile' ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />}
Сохранить
</button>
<button
onClick={() => { setIsEditingProfile(false); setProfileForm({ name: user.name }); }}
className="flex items-center gap-1.5 px-3 py-1.5 bg-surface border border-border text-secondary rounded-lg text-sm hover:text-primary transition-all"
>
<X className="w-4 h-4" />
Отмена
</button>
</div>
</div>
) : (
<>
<div className="flex items-center gap-2">
<h3 className="text-lg font-medium text-primary">{user.name}</h3>
<span className={`text-xs font-medium px-2 py-0.5 rounded ${
user.tier === 'business'
? 'bg-amber-500/20 text-amber-400'
: user.tier === 'pro'
? 'bg-accent/20 text-accent'
: 'bg-surface text-muted'
}`}>
{user.tier === 'business' ? 'Business' : user.tier === 'pro' ? 'Pro' : 'Free'}
</span>
</div>
<p className="text-sm text-muted mt-0.5">{user.email}</p>
<button
onClick={() => setIsEditingProfile(true)}
className="mt-2 text-sm text-accent hover:text-accent-hover transition-colors"
>
Редактировать профиль
</button>
</>
)}
</div>
</div>
</div>
</Section>
{/* Email Section */}
<Section title="Email" icon={Mail}>
<div className="p-4 bg-elevated/40 border border-border/40 rounded-xl">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-primary">{user.email}</p>
<p className="text-xs text-muted mt-0.5">
{user.emailVerified ? (
<span className="text-success">Подтверждён</span>
) : (
<span className="text-warning">Не подтверждён</span>
)}
</p>
</div>
{!user.emailVerified && (
<button className="px-3 py-1.5 text-sm text-accent hover:text-accent-hover transition-colors">
Подтвердить
</button>
)}
</div>
</div>
</Section>
{/* Password Section */}
<Section title="Безопасность" icon={Key}>
<div className="p-4 bg-elevated/40 border border-border/40 rounded-xl">
{isChangingPassword ? (
<div className="space-y-3">
<input
type="password"
value={passwordForm.currentPassword}
onChange={(e) => setPasswordForm({ ...passwordForm, currentPassword: e.target.value })}
className="w-full px-3 py-2 bg-surface border border-border rounded-lg text-sm text-primary focus:outline-none focus:border-accent"
placeholder="Текущий пароль"
/>
<input
type="password"
value={passwordForm.newPassword}
onChange={(e) => setPasswordForm({ ...passwordForm, newPassword: e.target.value })}
className="w-full px-3 py-2 bg-surface border border-border rounded-lg text-sm text-primary focus:outline-none focus:border-accent"
placeholder="Новый пароль"
/>
<input
type="password"
value={passwordForm.confirmPassword}
onChange={(e) => setPasswordForm({ ...passwordForm, confirmPassword: e.target.value })}
className="w-full px-3 py-2 bg-surface border border-border rounded-lg text-sm text-primary focus:outline-none focus:border-accent"
placeholder="Подтвердите пароль"
/>
<div className="flex gap-2">
<button
onClick={handlePasswordChange}
disabled={loading === 'password'}
className="flex items-center gap-1.5 px-3 py-1.5 bg-accent text-white rounded-lg text-sm hover:bg-accent-hover transition-all disabled:opacity-50"
>
{loading === 'password' ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />}
Сохранить
</button>
<button
onClick={() => { setIsChangingPassword(false); setPasswordForm({ currentPassword: '', newPassword: '', confirmPassword: '' }); }}
className="flex items-center gap-1.5 px-3 py-1.5 bg-surface border border-border text-secondary rounded-lg text-sm hover:text-primary transition-all"
>
<X className="w-4 h-4" />
Отмена
</button>
</div>
</div>
) : (
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-primary">Пароль</p>
<p className="text-xs text-muted mt-0.5"></p>
</div>
<button
onClick={() => setIsChangingPassword(true)}
className="px-3 py-1.5 text-sm text-accent hover:text-accent-hover transition-colors"
>
Изменить
</button>
</div>
)}
</div>
</Section>
{/* Session Section */}
<Section title="Сессии" icon={LogOut}>
<div className="space-y-3">
<button
onClick={handleLogout}
disabled={loading === 'logout'}
className="w-full flex items-center justify-center gap-2 px-4 py-3 text-sm bg-surface/40 border border-border/50 text-secondary rounded-xl hover:bg-surface/60 hover:border-border hover:text-primary transition-all disabled:opacity-50"
>
{loading === 'logout' ? <Loader2 className="w-4 h-4 animate-spin" /> : <LogOut className="w-4 h-4" />}
Выйти из аккаунта
</button>
<button
onClick={handleLogoutAll}
disabled={loading === 'logoutAll'}
className="w-full flex items-center justify-center gap-2 px-4 py-3 text-sm bg-warning/5 border border-warning/20 text-warning rounded-xl hover:bg-warning/10 hover:border-warning/30 transition-all disabled:opacity-50"
>
{loading === 'logoutAll' ? <Loader2 className="w-4 h-4 animate-spin" /> : <LogOut className="w-4 h-4" />}
Выйти со всех устройств
</button>
</div>
</Section>
{/* Delete Account */}
<Section title="Опасная зона" icon={Trash2}>
<button className="w-full flex items-center justify-center gap-2 px-4 py-3 text-sm bg-error/5 border border-error/20 text-error rounded-xl hover:bg-error/10 hover:border-error/30 transition-all">
<Trash2 className="w-4 h-4" />
Удалить аккаунт
</button>
</Section>
</div>
);
}
function Section({ title, icon: Icon, children }: { title: string; icon: React.ElementType; children: React.ReactNode }) {
return (
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
className="space-y-3"
>
<div className="flex items-center gap-2">
<Icon className="w-4 h-4 text-muted" />
<h2 className="text-xs font-semibold text-muted uppercase tracking-wider">{title}</h2>
</div>
{children}
</motion.div>
);
}

View File

@@ -0,0 +1,326 @@
'use client';
import { useState } from 'react';
import { motion } from 'framer-motion';
import { Wallet, CreditCard, Plus, Check, Zap, Crown, Building2, ArrowRight, Receipt, Download, Clock } from 'lucide-react';
import { useAuth } from '@/lib/contexts/AuthContext';
interface Plan {
id: string;
name: string;
price: number;
priceMonthly: number;
icon: React.ElementType;
color: string;
features: string[];
limits: {
apiRequests: string;
llmRequests: string;
storage: string;
};
}
const plans: Plan[] = [
{
id: 'free',
name: 'Free',
price: 0,
priceMonthly: 0,
icon: Zap,
color: 'text-muted',
features: ['Базовый поиск', 'История запросов', 'Ограниченный AI'],
limits: {
apiRequests: '1,000/день',
llmRequests: '50/день',
storage: '100 MB',
},
},
{
id: 'pro',
name: 'Pro',
price: 990,
priceMonthly: 990,
icon: Crown,
color: 'text-accent',
features: ['Расширенный поиск', 'Приоритетный AI', 'Экспорт данных', 'API доступ'],
limits: {
apiRequests: '10,000/день',
llmRequests: '500/день',
storage: '1 GB',
},
},
{
id: 'business',
name: 'Business',
price: 4990,
priceMonthly: 4990,
icon: Building2,
color: 'text-amber-400',
features: ['Всё из Pro', 'Безлимитный AI', 'Приоритетная поддержка', 'Команды', 'SLA 99.9%'],
limits: {
apiRequests: '100,000/день',
llmRequests: '5,000/день',
storage: '10 GB',
},
},
];
const mockTransactions = [
{ id: '1', date: '2026-02-28', amount: 990, type: 'subscription', description: 'Подписка Pro' },
{ id: '2', date: '2026-02-15', amount: 500, type: 'topup', description: 'Пополнение баланса' },
{ id: '3', date: '2026-01-28', amount: 990, type: 'subscription', description: 'Подписка Pro' },
];
export function BillingTab() {
const { user } = useAuth();
const [selectedPlan, setSelectedPlan] = useState<string | null>(null);
const [showTopup, setShowTopup] = useState(false);
const [topupAmount, setTopupAmount] = useState('');
if (!user) return null;
const currentPlan = plans.find(p => p.id === user.tier) || plans[0];
const handleUpgrade = (planId: string) => {
setSelectedPlan(planId);
};
const handleTopup = () => {
const amount = parseInt(topupAmount, 10);
if (isNaN(amount) || amount < 100) return;
setShowTopup(false);
setTopupAmount('');
};
return (
<div className="space-y-6">
{/* Balance Card */}
<Section title="Баланс" icon={Wallet}>
<div className="p-4 bg-gradient-to-br from-accent/20 via-accent/10 to-transparent border border-accent/30 rounded-xl">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-muted">Текущий баланс</p>
<p className="text-3xl font-bold text-primary mt-1">{(user.balance ?? 0).toLocaleString('ru-RU')} </p>
</div>
<button
onClick={() => setShowTopup(!showTopup)}
className="flex items-center gap-2 px-4 py-2.5 bg-accent text-white rounded-xl hover:bg-accent-hover transition-all text-sm font-medium"
>
<Plus className="w-4 h-4" />
Пополнить
</button>
</div>
{showTopup && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
className="mt-4 pt-4 border-t border-accent/20"
>
<div className="flex gap-2 mb-3">
{[100, 500, 1000, 5000].map((amount) => (
<button
key={amount}
onClick={() => setTopupAmount(amount.toString())}
className={`flex-1 py-2 rounded-lg text-sm font-medium transition-all ${
topupAmount === amount.toString()
? 'bg-accent text-white'
: 'bg-surface/50 text-secondary hover:text-primary hover:bg-surface'
}`}
>
{amount}
</button>
))}
</div>
<div className="flex gap-2">
<input
type="number"
value={topupAmount}
onChange={(e) => setTopupAmount(e.target.value)}
placeholder="Сумма"
className="flex-1 px-3 py-2 bg-surface border border-border rounded-lg text-sm text-primary focus:outline-none focus:border-accent"
/>
<button
onClick={handleTopup}
disabled={!topupAmount || parseInt(topupAmount, 10) < 100}
className="px-4 py-2 bg-accent text-white rounded-lg text-sm font-medium hover:bg-accent-hover transition-all disabled:opacity-50"
>
Оплатить
</button>
</div>
<p className="text-xs text-muted mt-2">Минимальная сумма: 100 </p>
</motion.div>
)}
</div>
</Section>
{/* Current Plan */}
<Section title="Текущий тариф" icon={currentPlan.icon}>
<div className="p-4 bg-elevated/40 border border-border/40 rounded-xl">
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-3">
<div className={`w-10 h-10 rounded-xl bg-surface flex items-center justify-center ${currentPlan.color}`}>
<currentPlan.icon className="w-5 h-5" />
</div>
<div>
<h3 className="font-medium text-primary">{currentPlan.name}</h3>
<p className="text-sm text-muted">
{currentPlan.price === 0 ? 'Бесплатно' : `${currentPlan.price.toLocaleString('ru-RU')} ₽/мес`}
</p>
</div>
</div>
{user.tier !== 'business' && (
<button
onClick={() => handleUpgrade(user.tier === 'free' ? 'pro' : 'business')}
className="flex items-center gap-1.5 px-3 py-1.5 bg-accent/10 text-accent rounded-lg text-sm font-medium hover:bg-accent/20 transition-all"
>
Улучшить
<ArrowRight className="w-4 h-4" />
</button>
)}
</div>
<div className="grid grid-cols-3 gap-3">
<div className="p-3 bg-surface/30 rounded-lg">
<p className="text-xs text-muted">API запросы</p>
<p className="text-sm font-medium text-primary mt-0.5">{currentPlan.limits.apiRequests}</p>
</div>
<div className="p-3 bg-surface/30 rounded-lg">
<p className="text-xs text-muted">AI запросы</p>
<p className="text-sm font-medium text-primary mt-0.5">{currentPlan.limits.llmRequests}</p>
</div>
<div className="p-3 bg-surface/30 rounded-lg">
<p className="text-xs text-muted">Хранилище</p>
<p className="text-sm font-medium text-primary mt-0.5">{currentPlan.limits.storage}</p>
</div>
</div>
</div>
</Section>
{/* Plans Comparison */}
{selectedPlan && (
<Section title="Выбор тарифа" icon={Crown}>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
{plans.map((plan) => (
<motion.div
key={plan.id}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className={`p-4 rounded-xl border transition-all cursor-pointer ${
selectedPlan === plan.id
? 'bg-accent/10 border-accent'
: 'bg-elevated/40 border-border/40 hover:border-border'
} ${user.tier === plan.id ? 'ring-2 ring-accent/50' : ''}`}
onClick={() => setSelectedPlan(plan.id)}
>
<div className="flex items-center gap-2 mb-3">
<plan.icon className={`w-5 h-5 ${plan.color}`} />
<span className="font-medium text-primary">{plan.name}</span>
{user.tier === plan.id && (
<span className="text-xs bg-accent/20 text-accent px-1.5 py-0.5 rounded">Текущий</span>
)}
</div>
<p className="text-2xl font-bold text-primary mb-3">
{plan.price === 0 ? 'Бесплатно' : `${plan.price.toLocaleString('ru-RU')}`}
{plan.price > 0 && <span className="text-sm font-normal text-muted">/мес</span>}
</p>
<ul className="space-y-2">
{plan.features.map((feature, idx) => (
<li key={idx} className="flex items-center gap-2 text-sm text-secondary">
<Check className="w-4 h-4 text-accent flex-shrink-0" />
{feature}
</li>
))}
</ul>
{user.tier !== plan.id && plan.id !== 'free' && (
<button
onClick={(e) => { e.stopPropagation(); handleUpgrade(plan.id); }}
className="w-full mt-4 py-2 bg-accent text-white rounded-lg text-sm font-medium hover:bg-accent-hover transition-all"
>
{plans.findIndex(p => p.id === user.tier) < plans.findIndex(p => p.id === plan.id) ? 'Улучшить' : 'Выбрать'}
</button>
)}
</motion.div>
))}
</div>
</Section>
)}
{/* Payment Methods */}
<Section title="Способы оплаты" icon={CreditCard}>
<div className="p-4 bg-elevated/40 border border-border/40 rounded-xl">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-surface flex items-center justify-center">
<CreditCard className="w-5 h-5 text-muted" />
</div>
<p className="text-sm text-muted">Карты не добавлены</p>
</div>
<button className="flex items-center gap-1.5 px-3 py-1.5 bg-surface border border-border text-secondary rounded-lg text-sm hover:text-primary hover:border-border/80 transition-all">
<Plus className="w-4 h-4" />
Добавить
</button>
</div>
</div>
</Section>
{/* Transaction History */}
<Section title="История платежей" icon={Receipt}>
<div className="space-y-2">
{mockTransactions.length === 0 ? (
<div className="p-4 bg-elevated/40 border border-border/40 rounded-xl text-center">
<Clock className="w-8 h-8 text-muted mx-auto mb-2" />
<p className="text-sm text-muted">История платежей пуста</p>
</div>
) : (
mockTransactions.map((tx) => (
<div
key={tx.id}
className="flex items-center justify-between p-3 bg-elevated/40 border border-border/40 rounded-xl"
>
<div className="flex items-center gap-3">
<div className={`w-8 h-8 rounded-lg flex items-center justify-center ${
tx.type === 'topup' ? 'bg-success/10' : 'bg-accent/10'
}`}>
{tx.type === 'topup' ? (
<Plus className="w-4 h-4 text-success" />
) : (
<Receipt className="w-4 h-4 text-accent" />
)}
</div>
<div>
<p className="text-sm text-primary">{tx.description}</p>
<p className="text-xs text-muted">{new Date(tx.date).toLocaleDateString('ru-RU')}</p>
</div>
</div>
<div className="flex items-center gap-3">
<span className={`text-sm font-medium ${tx.type === 'topup' ? 'text-success' : 'text-primary'}`}>
{tx.type === 'topup' ? '+' : '-'}{tx.amount.toLocaleString('ru-RU')}
</span>
<button className="p-1.5 text-muted hover:text-secondary transition-colors">
<Download className="w-4 h-4" />
</button>
</div>
</div>
))
)}
</div>
</Section>
</div>
);
}
function Section({ title, icon: Icon, children }: { title: string; icon: React.ElementType; children: React.ReactNode }) {
return (
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
className="space-y-3"
>
<div className="flex items-center gap-2">
<Icon className="w-4 h-4 text-muted" />
<h2 className="text-xs font-semibold text-muted uppercase tracking-wider">{title}</h2>
</div>
{children}
</motion.div>
);
}

View File

@@ -0,0 +1,199 @@
'use client';
import { useState } from 'react';
import { motion } from 'framer-motion';
import { Shield, Zap, Scale, Sparkles, Download, Trash2, Bell, Eye, Languages, Plug, ChevronDown } from 'lucide-react';
import * as Switch from '@radix-ui/react-switch';
import { useLanguage, SupportedLanguage } from '@/lib/contexts/LanguageContext';
import { ConnectorsSettings } from '@/components/settings/ConnectorsSettings';
export function PreferencesTab() {
const [mode, setMode] = useState('balanced');
const [saveHistory, setSaveHistory] = useState(true);
const [personalization, setPersonalization] = useState(true);
const [notifications, setNotifications] = useState(false);
const [showConnectors, setShowConnectors] = useState(false);
const { language, setLanguage } = useLanguage();
return (
<div className="space-y-6">
{/* Default Mode */}
<Section title="Режим по умолчанию" icon={Zap}>
<div className="grid grid-cols-3 gap-2 sm:gap-3">
{[
{ id: 'speed', label: 'Быстрый', icon: Zap, desc: '~10 сек' },
{ id: 'balanced', label: 'Баланс', icon: Scale, desc: '~30 сек' },
{ id: 'quality', label: 'Качество', icon: Sparkles, desc: '~60 сек' },
].map((m) => (
<button
key={m.id}
onClick={() => setMode(m.id)}
className={`flex flex-col items-center gap-1 sm:gap-2 p-3 sm:p-4 rounded-xl border transition-all ${
mode === m.id
? 'active-gradient text-primary'
: 'bg-surface/30 border-border/30 text-muted hover:border-border hover:text-secondary'
}`}
>
<m.icon className={`w-4 h-4 sm:w-5 sm:h-5 ${mode === m.id ? 'text-gradient' : ''}`} />
<span className="text-xs sm:text-sm font-medium">{m.label}</span>
<span className="text-[10px] sm:text-xs text-faint">{m.desc}</span>
</button>
))}
</div>
</Section>
{/* Privacy & Data */}
<Section title="Приватность" icon={Shield}>
<div className="space-y-3">
<ToggleRow
icon={Eye}
label="Сохранять историю"
description="Автоматическое сохранение сессий"
checked={saveHistory}
onChange={setSaveHistory}
/>
<ToggleRow
icon={Sparkles}
label="Персонализация"
description="Улучшение на основе истории"
checked={personalization}
onChange={setPersonalization}
/>
<ToggleRow
icon={Bell}
label="Уведомления"
description="Уведомления об обновлениях"
checked={notifications}
onChange={setNotifications}
/>
</div>
</Section>
{/* Language */}
<Section title="Язык интерфейса" icon={Languages}>
<div className="grid grid-cols-2 gap-2 sm:gap-3">
{[
{ id: 'ru', label: 'Русский', flag: '🇷🇺' },
{ id: 'en', label: 'English', flag: '🇺🇸' },
].map((lang) => (
<button
key={lang.id}
onClick={() => setLanguage(lang.id as SupportedLanguage)}
className={`flex items-center gap-3 p-3 sm:p-4 rounded-xl border transition-all ${
language === lang.id
? 'active-gradient text-primary'
: 'bg-surface/30 border-border/30 text-muted hover:border-border hover:text-secondary'
}`}
>
<span className="text-lg">{lang.flag}</span>
<span className="text-sm font-medium">{lang.label}</span>
</button>
))}
</div>
</Section>
{/* Connectors */}
<Section title="Коннекторы" icon={Plug}>
<div className="space-y-3">
<p className="text-xs text-muted">
Подключите источники данных и каналы уведомлений для автономных задач в Лаптопе.
</p>
<button
onClick={() => setShowConnectors(!showConnectors)}
className="w-full flex items-center justify-between p-3 sm:p-4 bg-elevated/40 border border-border/40 rounded-xl hover:bg-elevated/60 hover:border-border transition-all"
>
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-indigo-500/10 flex items-center justify-center">
<Plug className="w-5 h-5 text-indigo-400" />
</div>
<div className="text-left">
<p className="text-sm font-medium text-primary">Настроить коннекторы</p>
<p className="text-xs text-muted">Поиск, данные, финансы, уведомления</p>
</div>
</div>
<ChevronDown className={`w-5 h-5 text-muted transition-transform ${showConnectors ? 'rotate-180' : ''}`} />
</button>
{showConnectors && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
className="pt-2"
>
<ConnectorsSettings />
</motion.div>
)}
</div>
</Section>
{/* Data Management */}
<Section title="Управление данными" icon={Download}>
<div className="flex flex-col sm:flex-row gap-3">
<button className="flex-1 flex items-center justify-center gap-2 px-4 py-3 text-sm bg-surface/40 border border-border/50 text-secondary rounded-xl hover:bg-surface/60 hover:border-border hover:text-primary transition-all">
<Download className="w-4 h-4" />
Экспорт данных
</button>
<button className="flex-1 flex items-center justify-center gap-2 px-4 py-3 text-sm bg-error/5 border border-error/20 text-error rounded-xl hover:bg-error/10 hover:border-error/30 transition-all">
<Trash2 className="w-4 h-4" />
Удалить всё
</button>
</div>
</Section>
{/* About */}
<div className="pt-6 border-t border-border/30">
<div className="text-center text-faint text-xs">
<p className="mb-1">GooSeek v1.0.0</p>
<p>AI-поиск нового поколения</p>
</div>
</div>
</div>
);
}
function Section({ title, icon: Icon, children }: { title: string; icon: React.ElementType; children: React.ReactNode }) {
return (
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
className="space-y-3 sm:space-y-4"
>
<div className="flex items-center gap-2">
<Icon className="w-4 h-4 text-muted" />
<h2 className="text-xs font-semibold text-muted uppercase tracking-wider">
{title}
</h2>
</div>
{children}
</motion.div>
);
}
interface ToggleRowProps {
icon: React.ElementType;
label: string;
description: string;
checked: boolean;
onChange: (v: boolean) => void;
}
function ToggleRow({ icon: Icon, label, description, checked, onChange }: ToggleRowProps) {
return (
<div className="flex items-center gap-3 sm:gap-4 p-3 sm:p-4 bg-elevated/40 border border-border/40 rounded-xl">
<div className="w-9 h-9 sm:w-10 sm:h-10 rounded-xl bg-surface/60 flex items-center justify-center flex-shrink-0">
<Icon className="w-4 h-4 text-secondary" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm text-primary truncate">{label}</p>
<p className="text-xs text-muted mt-0.5 truncate">{description}</p>
</div>
<Switch.Root
checked={checked}
onCheckedChange={onChange}
className="w-10 h-[22px] sm:w-11 sm:h-6 bg-surface/80 rounded-full relative transition-colors data-[state=checked]:active-gradient border border-border flex-shrink-0"
>
<Switch.Thumb className="block w-[18px] h-[18px] sm:w-5 sm:h-5 bg-secondary rounded-full transition-transform translate-x-0.5 data-[state=checked]:translate-x-[18px] sm:data-[state=checked]:translate-x-[22px] data-[state=checked]:progress-gradient" />
</Switch.Root>
</div>
);
}

View File

@@ -0,0 +1,4 @@
export { AccountTab } from './AccountTab';
export { BillingTab } from './BillingTab';
export { PreferencesTab } from './PreferencesTab';
export { ConnectorsSettings } from './ConnectorsSettings';

View File

@@ -4,6 +4,7 @@ import type {
StreamEvent, StreamEvent,
Thread, Thread,
Space, Space,
SpaceMember,
FinanceMarket, FinanceMarket,
HeatmapData, HeatmapData,
TopMovers, TopMovers,
@@ -282,6 +283,72 @@ export async function deleteSpace(id: string): Promise<void> {
} }
} }
export async function fetchSpaceMembers(spaceId: string): Promise<SpaceMember[]> {
const response = await fetch(`${API_BASE}/api/v1/spaces/${spaceId}/members`, {
headers: getAuthHeaders(),
});
if (!response.ok) {
throw new Error(`Space members fetch failed: ${response.status}`);
}
const data = await response.json();
return data.members || [];
}
export async function inviteToSpace(spaceId: string, email: string, role: string = 'member'): Promise<{ inviteUrl: string }> {
const response = await fetch(`${API_BASE}/api/v1/spaces/${spaceId}/invite`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({ email, role }),
});
if (!response.ok) {
const data = await response.json().catch(() => ({}));
throw new Error(data.error || `Invite failed: ${response.status}`);
}
return response.json();
}
export async function removeSpaceMember(spaceId: string, userId: string): Promise<void> {
const response = await fetch(`${API_BASE}/api/v1/spaces/${spaceId}/members/${userId}`, {
method: 'DELETE',
headers: getAuthHeaders(),
});
if (!response.ok) {
throw new Error(`Remove member failed: ${response.status}`);
}
}
export async function acceptSpaceInvite(token: string): Promise<Space> {
const response = await fetch(`${API_BASE}/api/v1/spaces/invite/${token}/accept`, {
method: 'POST',
headers: getAuthHeaders(),
});
if (!response.ok) {
const data = await response.json().catch(() => ({}));
throw new Error(data.error || `Accept invite failed: ${response.status}`);
}
return response.json();
}
export async function fetchSpaceThreads(spaceId: string): Promise<Thread[]> {
const response = await fetch(`${API_BASE}/api/v1/spaces/${spaceId}/threads`, {
headers: getAuthHeaders(),
});
if (!response.ok) {
throw new Error(`Space threads fetch failed: ${response.status}`);
}
const data = await response.json();
return data.threads || [];
}
export async function fetchMarkets(): Promise<FinanceMarket[]> { export async function fetchMarkets(): Promise<FinanceMarket[]> {
const response = await fetch(`${API_BASE}/api/v1/markets`, { const response = await fetch(`${API_BASE}/api/v1/markets`, {
headers: getAuthHeaders(), headers: getAuthHeaders(),

View File

@@ -7,6 +7,7 @@ export interface User {
avatar?: string; avatar?: string;
role: 'user' | 'admin'; role: 'user' | 'admin';
tier: 'free' | 'pro' | 'business'; tier: 'free' | 'pro' | 'business';
balance: number;
emailVerified: boolean; emailVerified: boolean;
provider: string; provider: string;
createdAt: string; createdAt: string;

View File

@@ -30,6 +30,7 @@ export function useChat(options: UseChatOptions = {}) {
const mode = typeof sendOptions === 'string' ? sendOptions : sendOptions?.mode ?? 'balanced'; const mode = typeof sendOptions === 'string' ? sendOptions : sendOptions?.mode ?? 'balanced';
const webSearch = typeof sendOptions === 'object' ? sendOptions.webSearch : false; const webSearch = typeof sendOptions === 'object' ? sendOptions.webSearch : false;
const attachments = typeof sendOptions === 'object' ? sendOptions.attachments : []; const attachments = typeof sendOptions === 'object' ? sendOptions.attachments : [];
const model = typeof sendOptions === 'object' ? sendOptions.model : undefined;
const locale = getLanguageFromStorage(); const locale = getLanguageFromStorage();
if (!content.trim() || isLoading) return; if (!content.trim() || isLoading) return;
@@ -91,6 +92,7 @@ export function useChat(options: UseChatOptions = {}) {
locale, locale,
webSearch, webSearch,
attachments: attachmentInfos.length > 0 ? attachmentInfos : undefined, attachments: attachmentInfos.length > 0 ? attachmentInfos : undefined,
chatModel: model,
}); });
let fullContent = ''; let fullContent = '';

View File

@@ -55,13 +55,41 @@ export interface DiscoverItem {
export interface Space { export interface Space {
id: string; id: string;
userId: string;
name: string; name: string;
description?: string; description?: string;
instructions?: string; instructions?: string;
icon?: string;
color?: string;
focusMode?: FocusMode; focusMode?: FocusMode;
isPublic?: boolean; isPublic?: boolean;
createdAt: string; createdAt: string;
updatedAt?: string; updatedAt?: string;
threadCount?: number;
memberCount?: number;
members?: SpaceMember[];
isOwner?: boolean;
}
export interface SpaceMember {
id: string;
spaceId: string;
userId: string;
role: 'owner' | 'admin' | 'member';
email?: string;
name?: string;
avatar?: string;
joinedAt: string;
}
export interface SpaceInvite {
id: string;
spaceId: string;
email: string;
role: string;
invitedBy: string;
expiresAt: string;
createdAt: string;
} }
export type FocusMode = export type FocusMode =