Spaces:
Running

File size: 13,920 Bytes
1b99aeb
 
eaf22dd
1b99aeb
0235b53
1b99aeb
 
 
 
 
 
 
 
 
 
 
050010d
 
 
3f91467
1b99aeb
 
 
 
 
 
 
 
 
 
0235b53
eaf22dd
0235b53
eaf22dd
1b99aeb
 
 
 
 
 
 
 
 
 
 
c8fce60
 
1b99aeb
 
 
c8fce60
1b99aeb
 
 
 
 
0235b53
eaf22dd
0235b53
eaf22dd
 
1b99aeb
6bfac6b
1b99aeb
 
 
 
 
 
 
6bfac6b
 
 
 
 
 
 
 
 
1b99aeb
eaf22dd
1b99aeb
 
68688a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b99aeb
8cb08f2
 
1b99aeb
 
2f7ae1c
 
 
 
 
1b99aeb
 
 
eaf22dd
2f7ae1c
 
 
 
1b99aeb
 
 
 
2f7ae1c
dc7e33a
1b99aeb
 
2f7ae1c
 
 
 
 
 
1b99aeb
 
2f7ae1c
dc7e33a
1b99aeb
 
2f7ae1c
 
 
050010d
2f7ae1c
050010d
2f7ae1c
 
 
1b99aeb
 
2f7ae1c
 
 
 
 
 
1b99aeb
050010d
2f7ae1c
050010d
2f7ae1c
050010d
 
 
1b99aeb
 
3f91467
2f7ae1c
 
050010d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f7ae1c
050010d
2f7ae1c
1b99aeb
2f7ae1c
050010d
 
2f7ae1c
050010d
1b99aeb
 
eaf22dd
0235b53
2f7ae1c
 
 
 
 
 
eaf22dd
 
2f7ae1c
68688a7
2f7ae1c
 
 
 
 
 
 
 
 
 
 
eaf22dd
 
 
1b99aeb
 
 
 
 
2f7ae1c
 
 
 
 
 
1b99aeb
 
eaf22dd
0235b53
 
 
 
 
 
1b99aeb
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246

import { useState, useEffect } from 'react'
import { Search, Shield, User as UserIcon, LogIn, Check, X, Ban, Edit, Trash, Handshake } from 'lucide-react'
import { useToast } from '@/contexts/ToastContext'
import UserDetailsModal from './UserDetailsModal'

interface User {
    id: string
    email: string
    full_name: string
    is_active: boolean
    is_superuser: boolean
    is_verified: boolean
    role: string
    created_at: string
    tenant_name: string
    tenant_id?: string
    subscription_plan?: string
    subscription_status?: string
    subscription_end?: string
    partner_status: string | null
    referral_code: string | null
}

export default function UsersTab() {
    const [users, setUsers] = useState<User[]>([])
    const [loading, setLoading] = useState(true)
    const [searchQuery, setSearchQuery] = useState('')
    const toast = useToast()

    // Modal State
    const [selectedUser, setSelectedUser] = useState<User | null>(null)
    const [showDetailsModal, setShowDetailsModal] = useState(false)

    useEffect(() => {
        loadUsers()
    }, [])

    const loadUsers = async () => {
        try {
            const res = await fetch('/api/v1/admin/users', {
                headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` }
            })
            if (res.ok) {
                setUsers(await res.json())
            } else {
                throw new Error(res.statusText)
            }
        } catch (error) {
            console.error('Error loading users:', error)
            toast.error('Ошибка загрузки', 'Не удалось получить список пользователей')
        } finally {
            setLoading(false)
        }
    }

    const openDetailsModal = (user: User) => {
        setSelectedUser(user)
        setShowDetailsModal(true)
    }

    const handleImpersonate = async (userId: string) => {
        if (!confirm('Вы уверены, что хотите войти под этим пользователем? Откроется новая вкладка.')) return
        try {
            const res = await fetch(`/api/v1/admin/users/${userId}/impersonate`, {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` }
            })
            if (res.ok) {
                const data = await res.json()
                // Open in NEW TAB with token in URL - admin stays logged in!
                const newWindow = window.open(`/auth/impersonate?token=${data.access_token}`, '_blank')
                if (newWindow) {
                    toast.success('Успех', 'Новая вкладка открыта с аккаунтом пользователя')
                } else {
                    // Popup blocked - fallback to copying token
                    navigator.clipboard.writeText(data.access_token)
                    toast.info('Popup заблокирован', 'Токен скопирован в буфер. Откройте /auth/impersonate вручную.')
                }
            }
        } catch (error) { toast.error('Ошибка', 'Ошибка сети') }
    }

    const handleDeleteUser = async (userId: string, email: string) => {
        if (!confirm(`Удалить пользователя ${email}? Это действие необратимо.`)) return
        try {
            const res = await fetch(`/api/v1/admin/users/${userId}`, {
                method: 'DELETE',
                headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` }
            })
            if (res.ok) {
                toast.success('Удалено', `Пользователь ${email} удален`)
                loadUsers()
            } else {
                const err = await res.json()
                toast.error('Ошибка', err.detail || 'Не удалось удалить')
            }
        } catch (error) { toast.error('Ошибка', 'Ошибка сети') }
    }

    const filteredUsers = users.filter(u =>
        (u.email ?? '').toLowerCase().includes(searchQuery.toLowerCase()) ||
        (u.full_name ?? '').toLowerCase().includes(searchQuery.toLowerCase())
    )

    if (loading) return (
        <div className="flex items-center justify-center p-12">
            <div className="w-8 h-8 rounded-full border-2 border-indigo-500 border-t-transparent animate-spin"></div>
        </div>
    )

    return (
        <div className="space-y-6">

            {/* Controls */}
            <div className="flex items-center justify-between gap-4">
                <div className="relative flex-1 max-w-sm">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 w-4 h-4" />
                    <input
                        type="text"
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        placeholder="Поиск"
                        className="w-full pl-10 pr-4 py-2.5 bg-surface-elevated border border-white/10 rounded-xl text-sm text-white placeholder:text-slate-600 focus:border-indigo-500/50 focus:ring-1 focus:ring-indigo-500/50 outline-none transition-all"
                    />
                </div>
                <button
                    onClick={() => {/* Implement Add User */ toast.info('Функция в разработке', 'Скоро будет доступна') }}
                    className="px-4 py-2.5 bg-[#1A1B26] hover:bg-[#222332] text-slate-300 hover:text-white border border-white/10 rounded-xl text-sm font-medium transition-colors"
                >
                    Добавить пользователя
                </button>
            </div>

            {/* Table - Reference Design */}
            <div className="bg-surface-elevated rounded-2xl border border-white/10 overflow-hidden">
                <div className="overflow-x-auto">
                    <table className="w-full">
                        <thead>
                            <tr className="border-b border-white/10">
                                <th className="px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider bg-white/5">ID</th>
                                <th className="px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider bg-white/5">Компания</th>
                                <th className="px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider bg-white/5">Email</th>
                                <th className="px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider bg-white/5">Тариф</th>
                                <th className="px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider bg-white/5">Роль</th>
                                <th className="px-6 py-4 text-left text-xs font-bold text-slate-400 uppercase tracking-wider bg-white/5">Статус</th>
                                <th className="px-6 py-4 text-right text-xs font-bold text-slate-400 uppercase tracking-wider bg-white/5">Действия</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-white/5">
                            {filteredUsers.map((user, index) => (
                                <tr key={user.id} className="group hover:bg-white/5 transition-colors cursor-pointer" onClick={() => openDetailsModal(user)}>
                                    <td className="px-6 py-4 text-sm text-slate-500 font-mono">
                                        {index + 1}
                                    </td>
                                    <td className="px-6 py-4">
                                        <div className="flex flex-col">
                                            <span className="text-sm font-medium text-slate-300 group-hover:text-white transition-colors">
                                                {user.tenant_name || '—'}
                                            </span>
                                            {user.full_name && (
                                                <span className="text-xs text-slate-500">{user.full_name}</span>
                                            )}
                                        </div>
                                    </td>
                                    <td className="px-6 py-4 text-sm text-slate-400 group-hover:text-slate-300 transition-colors max-w-[150px] truncate">
                                        {user.email}
                                    </td>
                                    <td className="px-6 py-4">
                                        {(() => {
                                            const plan = user.subscription_plan?.toLowerCase() || 'trial'
                                            const planConfig: Record<string, { bg: string, text: string, label: string }> = {
                                                trial: { bg: 'bg-slate-500/10', text: 'text-slate-400', label: 'Trial' },
                                                start: { bg: 'bg-blue-500/10', text: 'text-blue-400', label: 'Start' },
                                                growth: { bg: 'bg-purple-500/10', text: 'text-purple-400', label: 'Growth' },
                                                enterprise: { bg: 'bg-amber-500/10', text: 'text-amber-400', label: 'Enterprise' },
                                            }
                                            const config = planConfig[plan] || planConfig.trial
                                            return (
                                                <span className={`inline-flex px-2.5 py-1 rounded-full text-xs font-bold border border-white/10 ${config.bg} ${config.text}`}>
                                                    {config.label}
                                                </span>
                                            )
                                        })()}
                                    </td>
                                    <td className="px-6 py-4 text-sm text-slate-400">
                                        {user.is_superuser || user.role === 'admin' ? 'Админ' : user.role === 'OWNER' ? 'Владелец' : 'Менеджер'}
                                    </td>
                                    <td className="px-6 py-4">
                                        <div className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium border ${user.is_active
                                            ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20'
                                            : 'bg-red-500/10 text-red-400 border-red-500/20'
                                            }`}>
                                            {user.is_active ? 'Активен' : 'Заблокирован'}
                                        </div>
                                    </td>
                                    <td className="px-6 py-4 text-right">
                                        <div className="flex justify-end gap-2" onClick={e => e.stopPropagation()}>
                                            <button
                                                onClick={() => openDetailsModal(user)}
                                                className="p-2 text-slate-500 hover:text-indigo-400 hover:bg-indigo-500/10 rounded-lg border border-transparent hover:border-indigo-500/20 transition-all"
                                                title="Редактировать"
                                            >
                                                <Edit className="w-4 h-4" />
                                            </button>

                                            <button
                                                onClick={() => handleDeleteUser(user.id, user.email)}
                                                className="p-2 text-slate-500 hover:text-red-400 hover:bg-red-500/10 rounded-lg border border-transparent hover:border-red-500/20 transition-all"
                                                title="Удалить"
                                            >
                                                <Trash className="w-4 h-4" />
                                            </button>

                                            <button
                                                onClick={() => handleImpersonate(user.id)}
                                                className="p-2 text-slate-500 hover:text-white hover:bg-white/10 rounded-lg border border-transparent hover:border-white/10 transition-all ml-1"
                                                title="Войти как"
                                            >
                                                <LogIn className="w-4 h-4" />
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>

                    {filteredUsers.length === 0 && (
                        <div className="p-8 text-center text-slate-500 text-sm">
                            Пользователи не найдены
                        </div>
                    )}
                </div>
            </div>

            <UserDetailsModal
                user={selectedUser}
                isOpen={showDetailsModal}
                onClose={() => setShowDetailsModal(false)}
                onUpdate={loadUsers}
            />
        </div>
    )
}