admin company page
This commit is contained in:
119
server.py
119
server.py
@@ -2161,6 +2161,125 @@ async def create_or_update_company(
|
||||
return dict(cursor.fetchone())
|
||||
|
||||
|
||||
@app.get("/api/admin/companies")
|
||||
async def get_all_companies_admin(
|
||||
user_id: int = Depends(get_current_user),
|
||||
page: int = 1,
|
||||
limit: int = 10,
|
||||
search: str = None
|
||||
):
|
||||
"""Получение всех компаний для админки"""
|
||||
try:
|
||||
print(f"👑 Админ {user_id} запрашивает список компаний")
|
||||
|
||||
with get_db() as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Проверка прав администратора
|
||||
cursor.execute("SELECT is_admin FROM users WHERE id = ?", (user_id,))
|
||||
user = cursor.fetchone()
|
||||
if not user or not user["is_admin"]:
|
||||
raise HTTPException(status_code=403, detail="Доступ запрещен")
|
||||
|
||||
# Базовый запрос
|
||||
query = """
|
||||
SELECT
|
||||
c.*,
|
||||
u.full_name as owner_name,
|
||||
(SELECT COUNT(*) FROM vacancies WHERE user_id = c.user_id AND is_active = 1) as vacancies_count
|
||||
FROM companies c
|
||||
JOIN users u ON c.user_id = u.id
|
||||
WHERE 1=1
|
||||
"""
|
||||
params = []
|
||||
|
||||
# Поиск
|
||||
if search:
|
||||
query += " AND (c.name LIKE ? OR c.email LIKE ? OR u.full_name LIKE ?)"
|
||||
search_term = f"%{search}%"
|
||||
params.extend([search_term, search_term, search_term])
|
||||
|
||||
# Сортировка
|
||||
query += " ORDER BY c.created_at DESC"
|
||||
|
||||
# Пагинация
|
||||
offset = (page - 1) * limit
|
||||
query += " LIMIT ? OFFSET ?"
|
||||
params.extend([limit, offset])
|
||||
|
||||
cursor.execute(query, params)
|
||||
companies = cursor.fetchall()
|
||||
|
||||
# Получаем общее количество
|
||||
count_query = "SELECT COUNT(*) FROM companies"
|
||||
if search:
|
||||
count_query += " WHERE name LIKE ? OR email LIKE ?"
|
||||
cursor.execute(count_query, [search_term, search_term])
|
||||
else:
|
||||
cursor.execute(count_query)
|
||||
total = cursor.fetchone()[0]
|
||||
|
||||
result = [dict(c) for c in companies]
|
||||
|
||||
return {
|
||||
"companies": result,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"total_pages": (total + limit - 1) // limit,
|
||||
"limit": limit
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f"❌ Ошибка при загрузке компаний: {e}")
|
||||
traceback.print_exc()
|
||||
raise HTTPException(status_code=500, detail=f"Внутренняя ошибка: {str(e)}")
|
||||
|
||||
|
||||
@app.delete("/api/admin/companies/{company_id}")
|
||||
async def delete_company_admin(
|
||||
company_id: int,
|
||||
user_id: int = Depends(get_current_user)
|
||||
):
|
||||
"""Удаление компании (только для админа)"""
|
||||
try:
|
||||
print(f"👑 Админ {user_id} пытается удалить компанию {company_id}")
|
||||
|
||||
with get_db() as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Проверка прав администратора
|
||||
cursor.execute("SELECT is_admin FROM users WHERE id = ?", (user_id,))
|
||||
user = cursor.fetchone()
|
||||
if not user or not user["is_admin"]:
|
||||
raise HTTPException(status_code=403, detail="Доступ запрещен")
|
||||
|
||||
# Проверяем существование компании
|
||||
cursor.execute("SELECT user_id FROM companies WHERE id = ?", (company_id,))
|
||||
company = cursor.fetchone()
|
||||
if not company:
|
||||
raise HTTPException(status_code=404, detail="Компания не найдена")
|
||||
|
||||
# Удаляем вакансии компании
|
||||
cursor.execute("DELETE FROM vacancies WHERE user_id = ?", (company["user_id"],))
|
||||
|
||||
# Удаляем компанию
|
||||
cursor.execute("DELETE FROM companies WHERE id = ?", (company_id,))
|
||||
|
||||
conn.commit()
|
||||
print(f"✅ Компания {company_id} успешно удалена")
|
||||
|
||||
return {"message": "Компания успешно удалена"}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f"❌ Ошибка при удалении компании {company_id}: {e}")
|
||||
traceback.print_exc()
|
||||
raise HTTPException(status_code=500, detail=f"Внутренняя ошибка: {str(e)}")
|
||||
|
||||
|
||||
@app.get("/api/companies/{company_id}")
|
||||
async def get_company_by_id(company_id: int):
|
||||
"""Получение информации о компании по ID (публичный эндпоинт)"""
|
||||
|
||||
Reference in New Issue
Block a user