feat: phone login, position badge, logout in profile, global search, admin chats

- Login: by phone number instead of username
- Position field: shown as badge next to name in members list, search, admin panel
- Logout: moved from sidebar to profile modal settings
- Sidebar search: global — shows matching users with one-click private chat
- Admin panel: new Чаты tab showing all chats with delete, position/phone in user form
- Backend: /api/admin/chats endpoint, position column migration, phone login support

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Ai
2026-05-22 12:17:46 +03:00
parent 8993a9f6ce
commit 8e5c4cd67d
11 changed files with 215 additions and 62 deletions

View File

@@ -204,12 +204,15 @@ export default function ChatInfoPanel({ chat, onClose, onRefresh }: Props) {
<div key={m.id} className="flex items-center gap-2 py-1.5 px-2 rounded-lg hover:bg-gray-50 group">
<Avatar name={m.displayName} color={m.avatarColor} size="sm" online={onlineUsers.has(m.id)} />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1 text-sm font-medium text-gray-900">
{m.displayName}
<div className="flex items-center gap-1 flex-wrap text-sm font-medium text-gray-900">
<span className="truncate">{m.displayName}</span>
{roleIcon(m.role)}
{!m.canSendMessages && <Ban className="w-3 h-3 text-red-400" />}
</div>
<div className="text-xs text-gray-400">@{m.username}</div>
<div className="flex items-center gap-1.5">
<span className="text-xs text-gray-400">@{m.username}</span>
{m.position && <span className="text-xs bg-blue-50 text-blue-600 px-1.5 py-0.5 rounded-full">{m.position}</span>}
</div>
</div>
{isOwnerOrAdmin && m.id !== me?.id && m.role !== 'owner' && (
<div className="hidden group-hover:flex gap-1">

View File

@@ -1,6 +1,8 @@
import { useState, useRef } from 'react';
import { X, Camera, Trash2, Save, Lock } from 'lucide-react';
import { X, Camera, Trash2, Save, Lock, LogOut } from 'lucide-react';
import { useStore } from '../store';
import { useNavigate } from 'react-router-dom';
import { wsClient } from '../api/ws';
import api from '../api/client';
import Avatar from './Avatar';
@@ -9,10 +11,12 @@ interface Props {
}
export default function ProfileModal({ onClose }: Props) {
const { user, setUser } = useStore();
const { user, setUser, logout } = useStore();
const navigate = useNavigate();
const [displayName, setDisplayName] = useState(user?.displayName || '');
const [bio, setBio] = useState(user?.bio || '');
const [phone, setPhone] = useState(user?.phone || '');
const [position, setPosition] = useState(user?.position || '');
const [password, setPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [saving, setSaving] = useState(false);
@@ -26,7 +30,7 @@ export default function ProfileModal({ onClose }: Props) {
setError('');
setSuccess('');
try {
const body: any = { displayName, bio, phone };
const body: any = { displayName, bio, phone, position: position || null };
if (newPassword) {
if (!password) { setError('Введите текущий пароль'); setSaving(false); return; }
body.password = password;
@@ -162,6 +166,15 @@ export default function ProfileModal({ onClose }: Props) {
placeholder="+7..."
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-500 mb-1">Должность</label>
<input
value={position}
onChange={e => setPosition(e.target.value)}
className="w-full px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-200"
placeholder="Менеджер, Директор..."
/>
</div>
</div>
{/* Password */}
@@ -190,7 +203,7 @@ export default function ProfileModal({ onClose }: Props) {
{success && <p className="text-green-500 text-sm">{success}</p>}
</div>
<div className="p-4 border-t border-gray-100">
<div className="p-4 border-t border-gray-100 space-y-2">
<button
onClick={handleSave}
disabled={saving}
@@ -199,6 +212,13 @@ export default function ProfileModal({ onClose }: Props) {
<Save className="w-4 h-4" />
{saving ? 'Сохранение...' : 'Сохранить'}
</button>
<button
onClick={() => { wsClient.disconnect(); logout(); navigate('/login'); }}
className="w-full flex items-center justify-center gap-2 text-red-500 hover:bg-red-50 py-2.5 rounded-xl text-sm transition-colors"
>
<LogOut className="w-4 h-4" />
Выйти
</button>
</div>
</div>
</div>

View File

@@ -8,21 +8,32 @@ interface Props { onClose: () => void; }
interface UserRow {
id: string; username: string; displayName: string; avatarColor: string;
isAdmin: boolean; isActive: boolean; lastSeen: string; createdAt: string;
phone: string; position: string;
}
interface ChatRow {
id: string; type: string; title: string; avatarColor: string; avatar: string | null;
memberCount: number; messageCount: number; createdAt: string;
}
export default function AdminPanel({ onClose }: Props) {
const [tab, setTab] = useState<'users' | 'stats'>('users');
const [tab, setTab] = useState<'users' | 'chats' | 'stats'>('users');
const [users, setUsers] = useState<UserRow[]>([]);
const [chats, setChats] = useState<ChatRow[]>([]);
const [stats, setStats] = useState<any>(null);
const [showCreate, setShowCreate] = useState(false);
const [editUser, setEditUser] = useState<UserRow | null>(null);
useEffect(() => { loadUsers(); loadStats(); }, []);
useEffect(() => { loadUsers(); loadStats(); loadChats(); }, []);
async function loadUsers() {
const { data } = await api.get('/api/admin/users');
setUsers(data);
}
async function loadChats() {
const { data } = await api.get('/api/admin/chats');
setChats(data);
}
async function loadStats() {
const { data } = await api.get('/api/admin/stats');
setStats(data);
@@ -34,6 +45,12 @@ export default function AdminPanel({ onClose }: Props) {
loadUsers();
}
async function deleteChat(id: string) {
if (!confirm('Удалить чат?')) return;
await api.delete(`/api/admin/chats/${id}`);
loadChats();
}
async function toggleActive(u: UserRow) {
await api.put(`/api/admin/users/${u.id}`, { isActive: !u.isActive });
loadUsers();
@@ -51,7 +68,7 @@ export default function AdminPanel({ onClose }: Props) {
{/* Tabs */}
<div className="flex border-b border-gray-100 px-4">
{[['users','Пользователи'],['stats','Статистика']].map(([k,v]) => (
{[['users','Пользователи'],['chats','Чаты'],['stats','Статистика']].map(([k,v]) => (
<button key={k} onClick={() => setTab(k as any)}
className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors ${
tab === k ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'
@@ -85,12 +102,13 @@ export default function AdminPanel({ onClose }: Props) {
<div key={u.id} className={`flex items-center gap-3 p-3 rounded-xl border ${u.isActive ? 'border-gray-100 bg-white' : 'border-gray-100 bg-gray-50 opacity-60'}`}>
<Avatar name={u.displayName} color={u.avatarColor} size="sm" />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium text-sm text-gray-900">{u.displayName}</span>
{u.position && <span className="text-xs bg-purple-50 text-purple-600 px-1.5 py-0.5 rounded-full">{u.position}</span>}
{u.isAdmin && <span className="text-xs bg-blue-100 text-blue-600 px-1.5 py-0.5 rounded-full">admin</span>}
{!u.isActive && <span className="text-xs bg-gray-100 text-gray-500 px-1.5 py-0.5 rounded-full">заблокирован</span>}
</div>
<div className="text-xs text-gray-400">@{u.username}</div>
<div className="text-xs text-gray-400">@{u.username}{u.phone ? ` · ${u.phone}` : ''}</div>
</div>
<div className="flex items-center gap-1">
<button onClick={() => toggleActive(u)} title={u.isActive ? 'Заблокировать' : 'Активировать'}
@@ -112,6 +130,31 @@ export default function AdminPanel({ onClose }: Props) {
</>
)}
{tab === 'chats' && (
<div className="space-y-2">
{chats.map(c => (
<div key={c.id} className="flex items-center gap-3 p-3 rounded-xl border border-gray-100 bg-white">
<Avatar name={c.title || '?'} color={c.avatarColor} avatar={c.avatar} size="sm" />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-medium text-sm text-gray-900 truncate">{c.title || '(личный)'}</span>
<span className={`text-xs px-1.5 py-0.5 rounded-full ${
c.type === 'channel' ? 'bg-orange-50 text-orange-600' :
c.type === 'group' ? 'bg-purple-50 text-purple-600' :
'bg-gray-100 text-gray-500'
}`}>{c.type === 'channel' ? 'канал' : c.type === 'group' ? 'группа' : 'личный'}</span>
</div>
<div className="text-xs text-gray-400">{c.memberCount} участников · {c.messageCount} сообщений</div>
</div>
<button onClick={() => deleteChat(c.id)} className="p-1.5 rounded-lg hover:bg-red-50 text-gray-400 hover:text-red-500">
<Trash2 className="w-4 h-4" />
</button>
</div>
))}
{chats.length === 0 && <p className="text-center text-gray-400 text-sm py-8">Нет чатов</p>}
</div>
)}
{tab === 'stats' && stats && (
<div className="grid grid-cols-3 gap-4">
{[
@@ -137,6 +180,8 @@ function UserForm({ user, onSave, onCancel }: { user: UserRow | null; onSave: ()
const [form, setForm] = useState({
username: user?.username || '',
displayName: user?.displayName || '',
phone: user?.phone || '',
position: user?.position || '',
password: '',
isAdmin: user?.isAdmin || false,
});
@@ -151,6 +196,8 @@ function UserForm({ user, onSave, onCancel }: { user: UserRow | null; onSave: ()
if (user) {
await api.put(`/api/admin/users/${user.id}`, {
displayName: form.displayName,
phone: form.phone || undefined,
position: form.position || undefined,
isAdmin: form.isAdmin,
password: form.password || undefined,
});
@@ -174,6 +221,10 @@ function UserForm({ user, onSave, onCancel }: { user: UserRow | null; onSave: ()
)}
<input value={form.displayName} onChange={e => setForm({...form, displayName: e.target.value})}
placeholder="Имя" required className="px-3 py-2 border border-gray-200 rounded-lg text-sm" />
<input value={form.phone} onChange={e => setForm({...form, phone: e.target.value})}
type="tel" placeholder="Телефон +7..." className="px-3 py-2 border border-gray-200 rounded-lg text-sm" />
<input value={form.position} onChange={e => setForm({...form, position: e.target.value})}
placeholder="Должность" className="px-3 py-2 border border-gray-200 rounded-lg text-sm" />
<input value={form.password} onChange={e => setForm({...form, password: e.target.value})}
type="password" placeholder={user ? 'Новый пароль (необязательно)' : 'Пароль'}
required={!user} className="px-3 py-2 border border-gray-200 rounded-lg text-sm" />

View File

@@ -9,7 +9,7 @@ interface Props {
export default function LoginPage({ onLogin }: Props) {
const navigate = useNavigate();
const [username, setUsername] = useState('');
const [phone, setPhone] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
@@ -19,7 +19,7 @@ export default function LoginPage({ onLogin }: Props) {
setError('');
setLoading(true);
try {
const { data } = await api.post('/api/auth/login', { username, password });
const { data } = await api.post('/api/auth/login', { phone, password });
onLogin(data.token, data.user);
navigate('/');
} catch (err: any) {
@@ -43,14 +43,14 @@ export default function LoginPage({ onLogin }: Props) {
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Логин</label>
<label className="block text-sm font-medium text-gray-700 mb-1">Номер телефона</label>
<input
type="text"
value={username}
onChange={e => setUsername(e.target.value)}
type="tel"
value={phone}
onChange={e => setPhone(e.target.value)}
className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
placeholder="Введите логин"
autoComplete="username"
placeholder="+7..."
autoComplete="tel"
required
/>
</div>

View File

@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react';
import { Search, Edit, LogOut, Settings, Shield, Wifi, WifiOff } from 'lucide-react';
import { Search, Edit, Settings, Shield, Wifi, WifiOff, MessageCircle } from 'lucide-react';
import { useStore } from '../store';
import { useNavigate } from 'react-router-dom';
import { wsClient } from '../api/ws';
@@ -16,9 +16,10 @@ import { usePushNotifications } from '../hooks/usePushNotifications';
import { Chat } from '../types';
export default function MainLayout() {
const { user, chats, activeChat, setActiveChat, connected, logout, onlineUsers, updateChat } = useStore();
const { user, chats, activeChat, setActiveChat, connected, onlineUsers, updateChat, setChats } = useStore();
const navigate = useNavigate();
const [search, setSearch] = useState('');
const [searchUsers, setSearchUsers] = useState<any[]>([]);
const [showNew, setShowNew] = useState(false);
const [showAdmin, setShowAdmin] = useState(false);
const [showInfo, setShowInfo] = useState(false);
@@ -68,10 +69,32 @@ export default function MainLayout() {
setShowInfo(false);
}
function handleLogout() {
wsClient.disconnect();
logout();
navigate('/login');
// Global search: fetch users when query changes
useEffect(() => {
if (search.trim().length < 1) { setSearchUsers([]); return; }
const timer = setTimeout(async () => {
try {
const { data } = await api.get('/api/users');
const q = search.toLowerCase();
setSearchUsers(data.filter((u: any) =>
(u.displayName || '').toLowerCase().includes(q) ||
(u.username || '').toLowerCase().includes(q) ||
(u.phone || '').includes(q)
));
} catch {}
}, 200);
return () => clearTimeout(timer);
}, [search]);
async function openOrCreatePrivate(userId: string) {
try {
const { data } = await api.post(`/api/chats/private/${userId}`);
const { data: allChats } = await api.get('/api/chats');
setChats(allChats);
const chat = allChats.find((c: any) => c.id === data.id);
if (chat) openChat(chat);
setSearch('');
} catch {}
}
const filtered = chats.filter(c =>
@@ -119,10 +142,6 @@ export default function MainLayout() {
className="p-1.5 rounded-lg hover:bg-gray-100 text-gray-400 hover:text-gray-600" title="Новый чат">
<Edit className="w-4 h-4" />
</button>
<button onClick={handleLogout}
className="p-1.5 rounded-lg hover:bg-gray-100 text-gray-400 hover:text-red-500" title="Выйти">
<LogOut className="w-4 h-4" />
</button>
</div>
</div>
@@ -139,20 +158,44 @@ export default function MainLayout() {
{/* Chat List */}
<div className="flex-1 overflow-y-auto py-2 px-2 space-y-0.5">
{filtered.length === 0 && (
<div className="text-center text-gray-400 text-sm py-8">
{search ? 'Ничего не найдено' : 'Нет чатов. Создайте новый!'}
</div>
)}
{filtered.map(chat => (
<ChatListItem
key={chat.id}
chat={chat}
active={activeChat?.id === chat.id}
online={chat.type === 'private' && chat.privateUserId ? onlineUsers.has(chat.privateUserId) : undefined}
onClick={() => openChat(chat)}
onClick={() => { openChat(chat); setSearch(''); }}
/>
))}
{/* Global user search results */}
{search && searchUsers.length > 0 && (
<>
{filtered.length > 0 && <div className="px-2 pt-2 pb-1 text-xs font-semibold text-gray-400 uppercase tracking-wide">Пользователи</div>}
{searchUsers.map(u => (
<button key={u.id} onClick={() => openOrCreatePrivate(u.id)}
className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-gray-50 text-left">
<Avatar name={u.displayName} color={u.avatarColor} avatar={u.avatar} size="sm"
online={onlineUsers.has(u.id)} />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
<span className="text-sm font-medium text-gray-900 truncate">{u.displayName}</span>
{u.position && <span className="text-xs bg-blue-50 text-blue-600 px-1.5 py-0.5 rounded-full shrink-0">{u.position}</span>}
</div>
<div className="text-xs text-gray-400">@{u.username}</div>
</div>
<MessageCircle className="w-4 h-4 text-gray-300 shrink-0" />
</button>
))}
</>
)}
{search && filtered.length === 0 && searchUsers.length === 0 && (
<div className="text-center text-gray-400 text-sm py-8">Ничего не найдено</div>
)}
{!search && filtered.length === 0 && (
<div className="text-center text-gray-400 text-sm py-8">Нет чатов. Создайте новый!</div>
)}
</div>
</div>

View File

@@ -6,6 +6,7 @@ export interface User {
avatar?: string | null;
bio?: string;
phone?: string;
position?: string | null;
isAdmin: boolean;
lastSeen?: string;
online?: boolean;
@@ -17,6 +18,7 @@ export interface ChatMember {
displayName: string;
avatarColor: string;
avatar?: string | null;
position?: string | null;
role: 'owner' | 'admin' | 'member';
online: boolean;
lastSeen: string;