Spaces:
Running
Running
axeronis commited on
Commit ·
68688a7
1
Parent(s): 5a15bf8
Admin UX: Add delete user, change subscription plan
Browse filesBackend:
- PATCH /admin/users/{id} - update user profile + subscription plan
- DELETE /admin/users/{id} - delete user (preserves tenant)
Frontend:
- UserDetailsModal: subscription plan selector dropdown
- UsersTab: delete button with confirmation dialog
backend/app/api/admin.py
CHANGED
|
@@ -46,6 +46,7 @@ class AdminUpdateUserRequest(BaseModel):
|
|
| 46 |
role: Optional[str] = None
|
| 47 |
is_active: Optional[bool] = None
|
| 48 |
is_verified: Optional[bool] = None
|
|
|
|
| 49 |
|
| 50 |
class AdminCreatePartnerRequest(BaseModel):
|
| 51 |
company_name: str
|
|
@@ -289,6 +290,80 @@ async def list_all_users(
|
|
| 289 |
return response
|
| 290 |
|
| 291 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
class UpdatePartnerRequest(BaseModel):
|
| 293 |
status: Optional[str] = None # ACTIVE, PENDING, BANNED
|
| 294 |
commission_rate: Optional[float] = None
|
|
|
|
| 46 |
role: Optional[str] = None
|
| 47 |
is_active: Optional[bool] = None
|
| 48 |
is_verified: Optional[bool] = None
|
| 49 |
+
subscription_plan: Optional[str] = None # trial, start, growth, enterprise
|
| 50 |
|
| 51 |
class AdminCreatePartnerRequest(BaseModel):
|
| 52 |
company_name: str
|
|
|
|
| 290 |
return response
|
| 291 |
|
| 292 |
|
| 293 |
+
@router.patch("/users/{user_id}")
|
| 294 |
+
async def update_user(
|
| 295 |
+
user_id: UUID,
|
| 296 |
+
body: AdminUpdateUserRequest,
|
| 297 |
+
session: AsyncSession = Depends(get_async_session),
|
| 298 |
+
current_user: User = Depends(get_admin_user)
|
| 299 |
+
):
|
| 300 |
+
"""
|
| 301 |
+
Update user profile, status, role, and subscription plan.
|
| 302 |
+
"""
|
| 303 |
+
user = await session.get(User, user_id)
|
| 304 |
+
if not user:
|
| 305 |
+
raise HTTPException(status_code=404, detail="User not found")
|
| 306 |
+
|
| 307 |
+
# Update user fields
|
| 308 |
+
if body.role is not None:
|
| 309 |
+
user.role = body.role
|
| 310 |
+
if body.is_active is not None:
|
| 311 |
+
user.is_active = body.is_active
|
| 312 |
+
if body.is_verified is not None:
|
| 313 |
+
user.is_verified = body.is_verified
|
| 314 |
+
|
| 315 |
+
session.add(user)
|
| 316 |
+
|
| 317 |
+
# Update subscription plan on tenant if provided
|
| 318 |
+
if body.subscription_plan and user.tenant_id:
|
| 319 |
+
tenant = await session.get(Tenant, user.tenant_id)
|
| 320 |
+
if tenant:
|
| 321 |
+
tenant.subscription_plan = body.subscription_plan
|
| 322 |
+
tenant.subscription_status = "active" # Activate when admin changes plan
|
| 323 |
+
session.add(tenant)
|
| 324 |
+
logger.info(f"Admin updated tenant {tenant.id} plan to {body.subscription_plan}")
|
| 325 |
+
|
| 326 |
+
await session.commit()
|
| 327 |
+
await session.refresh(user)
|
| 328 |
+
|
| 329 |
+
return {"status": "ok", "message": f"User {user.email} updated"}
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
@router.delete("/users/{user_id}")
|
| 333 |
+
async def delete_user(
|
| 334 |
+
user_id: UUID,
|
| 335 |
+
session: AsyncSession = Depends(get_async_session),
|
| 336 |
+
current_user: User = Depends(get_admin_user)
|
| 337 |
+
):
|
| 338 |
+
"""
|
| 339 |
+
Delete a user permanently.
|
| 340 |
+
- Removes partner profile if exists
|
| 341 |
+
- Preserves tenant (to keep business data)
|
| 342 |
+
- Cannot delete yourself
|
| 343 |
+
"""
|
| 344 |
+
if user_id == current_user.id:
|
| 345 |
+
raise HTTPException(status_code=400, detail="Cannot delete yourself")
|
| 346 |
+
|
| 347 |
+
user = await session.get(User, user_id)
|
| 348 |
+
if not user:
|
| 349 |
+
raise HTTPException(status_code=404, detail="User not found")
|
| 350 |
+
|
| 351 |
+
# Delete partner profile if exists
|
| 352 |
+
stmt = select(Partner).where(Partner.user_id == user_id)
|
| 353 |
+
result = await session.execute(stmt)
|
| 354 |
+
partner = result.scalar_one_or_none()
|
| 355 |
+
if partner:
|
| 356 |
+
await session.delete(partner)
|
| 357 |
+
logger.info(f"Deleted partner profile for user {user.email}")
|
| 358 |
+
|
| 359 |
+
# Delete user
|
| 360 |
+
await session.delete(user)
|
| 361 |
+
await session.commit()
|
| 362 |
+
|
| 363 |
+
logger.warning(f"🗑️ Admin {current_user.email} deleted user {user.email}")
|
| 364 |
+
return {"status": "ok", "message": f"User {user.email} deleted permanently"}
|
| 365 |
+
|
| 366 |
+
|
| 367 |
class UpdatePartnerRequest(BaseModel):
|
| 368 |
status: Optional[str] = None # ACTIVE, PENDING, BANNED
|
| 369 |
commission_rate: Optional[float] = None
|
frontend/components/admin/UserDetailsModal.tsx
CHANGED
|
@@ -15,6 +15,7 @@ interface User {
|
|
| 15 |
partner_status: string | null
|
| 16 |
referral_code: string | null
|
| 17 |
tenant_id?: string
|
|
|
|
| 18 |
}
|
| 19 |
|
| 20 |
interface UserDetailsModalProps {
|
|
@@ -34,6 +35,9 @@ export default function UserDetailsModal({ user, isOpen, onClose, onUpdate }: Us
|
|
| 34 |
const [isActive, setIsActive] = useState(true)
|
| 35 |
const [isVerified, setIsVerified] = useState(false)
|
| 36 |
|
|
|
|
|
|
|
|
|
|
| 37 |
// Partner Form
|
| 38 |
const [partnerName, setPartnerName] = useState('')
|
| 39 |
|
|
@@ -42,6 +46,7 @@ export default function UserDetailsModal({ user, isOpen, onClose, onUpdate }: Us
|
|
| 42 |
setRole(user.role)
|
| 43 |
setIsActive(user.is_active)
|
| 44 |
setIsVerified(user.is_verified)
|
|
|
|
| 45 |
setPartnerName(user.tenant_name || '')
|
| 46 |
}
|
| 47 |
}, [user])
|
|
@@ -57,7 +62,7 @@ export default function UserDetailsModal({ user, isOpen, onClose, onUpdate }: Us
|
|
| 57 |
'Content-Type': 'application/json',
|
| 58 |
'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
|
| 59 |
},
|
| 60 |
-
body: JSON.stringify({ role, is_active: isActive, is_verified: isVerified })
|
| 61 |
})
|
| 62 |
if (res.ok) {
|
| 63 |
toast.success('Сохранено', 'Профиль обновлен')
|
|
@@ -158,6 +163,15 @@ export default function UserDetailsModal({ user, isOpen, onClose, onUpdate }: Us
|
|
| 158 |
<option value="admin">Super Admin</option>
|
| 159 |
</select>
|
| 160 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
<div>
|
| 162 |
<label className="text-xs font-bold text-slate-400 uppercase">Статус</label>
|
| 163 |
<div className="mt-2 flex items-center gap-2">
|
|
|
|
| 15 |
partner_status: string | null
|
| 16 |
referral_code: string | null
|
| 17 |
tenant_id?: string
|
| 18 |
+
subscription_plan?: string
|
| 19 |
}
|
| 20 |
|
| 21 |
interface UserDetailsModalProps {
|
|
|
|
| 35 |
const [isActive, setIsActive] = useState(true)
|
| 36 |
const [isVerified, setIsVerified] = useState(false)
|
| 37 |
|
| 38 |
+
// Subscription Plan
|
| 39 |
+
const [subscriptionPlan, setSubscriptionPlan] = useState('')
|
| 40 |
+
|
| 41 |
// Partner Form
|
| 42 |
const [partnerName, setPartnerName] = useState('')
|
| 43 |
|
|
|
|
| 46 |
setRole(user.role)
|
| 47 |
setIsActive(user.is_active)
|
| 48 |
setIsVerified(user.is_verified)
|
| 49 |
+
setSubscriptionPlan(user.subscription_plan || 'trial')
|
| 50 |
setPartnerName(user.tenant_name || '')
|
| 51 |
}
|
| 52 |
}, [user])
|
|
|
|
| 62 |
'Content-Type': 'application/json',
|
| 63 |
'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
|
| 64 |
},
|
| 65 |
+
body: JSON.stringify({ role, is_active: isActive, is_verified: isVerified, subscription_plan: subscriptionPlan })
|
| 66 |
})
|
| 67 |
if (res.ok) {
|
| 68 |
toast.success('Сохранено', 'Профиль обновлен')
|
|
|
|
| 163 |
<option value="admin">Super Admin</option>
|
| 164 |
</select>
|
| 165 |
</div>
|
| 166 |
+
<div>
|
| 167 |
+
<label className="text-xs font-bold text-slate-400 uppercase">Тариф подписки</label>
|
| 168 |
+
<select value={subscriptionPlan} onChange={e => setSubscriptionPlan(e.target.value)} className="w-full mt-1 p-2.5 border border-white/10 rounded-lg bg-slate-800 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50">
|
| 169 |
+
<option value="trial">Trial (Пробный)</option>
|
| 170 |
+
<option value="start">Start</option>
|
| 171 |
+
<option value="growth">Growth</option>
|
| 172 |
+
<option value="enterprise">Enterprise</option>
|
| 173 |
+
</select>
|
| 174 |
+
</div>
|
| 175 |
<div>
|
| 176 |
<label className="text-xs font-bold text-slate-400 uppercase">Статус</label>
|
| 177 |
<div className="mt-2 flex items-center gap-2">
|
frontend/components/admin/UsersTab.tsx
CHANGED
|
@@ -74,6 +74,23 @@ export default function UsersTab() {
|
|
| 74 |
} catch (error) { toast.error('Ошибка', 'Ошибка сети') }
|
| 75 |
}
|
| 76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
const filteredUsers = users.filter(u =>
|
| 78 |
(u.email ?? '').toLowerCase().includes(searchQuery.toLowerCase()) ||
|
| 79 |
(u.full_name ?? '').toLowerCase().includes(searchQuery.toLowerCase())
|
|
@@ -181,7 +198,7 @@ export default function UsersTab() {
|
|
| 181 |
</button>
|
| 182 |
|
| 183 |
<button
|
| 184 |
-
onClick={() =>
|
| 185 |
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"
|
| 186 |
title="Удалить"
|
| 187 |
>
|
|
|
|
| 74 |
} catch (error) { toast.error('Ошибка', 'Ошибка сети') }
|
| 75 |
}
|
| 76 |
|
| 77 |
+
const handleDeleteUser = async (userId: string, email: string) => {
|
| 78 |
+
if (!confirm(`Удалить пользователя ${email}? Это действие необратимо.`)) return
|
| 79 |
+
try {
|
| 80 |
+
const res = await fetch(`/api/v1/admin/users/${userId}`, {
|
| 81 |
+
method: 'DELETE',
|
| 82 |
+
headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` }
|
| 83 |
+
})
|
| 84 |
+
if (res.ok) {
|
| 85 |
+
toast.success('Удалено', `Пользователь ${email} удален`)
|
| 86 |
+
loadUsers()
|
| 87 |
+
} else {
|
| 88 |
+
const err = await res.json()
|
| 89 |
+
toast.error('Ошибка', err.detail || 'Не удалось удалить')
|
| 90 |
+
}
|
| 91 |
+
} catch (error) { toast.error('Ошибка', 'Ошибка сети') }
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
const filteredUsers = users.filter(u =>
|
| 95 |
(u.email ?? '').toLowerCase().includes(searchQuery.toLowerCase()) ||
|
| 96 |
(u.full_name ?? '').toLowerCase().includes(searchQuery.toLowerCase())
|
|
|
|
| 198 |
</button>
|
| 199 |
|
| 200 |
<button
|
| 201 |
+
onClick={() => handleDeleteUser(user.id, user.email)}
|
| 202 |
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"
|
| 203 |
title="Удалить"
|
| 204 |
>
|