bmc_hub/app/contacts/backend/router_simple.py

92 lines
2.8 KiB
Python

"""
Contact API Router - Simplified (Read-Only)
Only GET endpoints for now
"""
from fastapi import APIRouter, HTTPException, Query
from typing import Optional
from app.core.database import execute_query
import logging
logger = logging.getLogger(__name__)
router = APIRouter()
@router.get("/contacts")
async def get_contacts(
search: Optional[str] = None,
customer_id: Optional[int] = None,
is_active: Optional[bool] = None,
limit: int = Query(default=100, le=1000),
offset: int = Query(default=0, ge=0)
):
"""Get all contacts with optional filtering"""
try:
where_clauses = []
params = []
if search:
where_clauses.append("(first_name ILIKE %s OR last_name ILIKE %s OR email ILIKE %s)")
params.extend([f"%{search}%", f"%{search}%", f"%{search}%"])
if is_active is not None:
where_clauses.append("is_active = %s")
params.append(is_active)
where_sql = "WHERE " + " AND ".join(where_clauses) if where_clauses else ""
# Count total
count_query = f"SELECT COUNT(*) as count FROM contacts {where_sql}"
count_result = execute_query(count_query, tuple(params))
total = count_result[0]['count'] if count_result else 0
# Get contacts
query = f"""
SELECT
id, first_name, last_name, email, phone, mobile,
title, department, is_active, created_at, updated_at
FROM contacts
{where_sql}
ORDER BY first_name, last_name
LIMIT %s OFFSET %s
"""
params.extend([limit, offset])
contacts = execute_query(query, tuple(params))
return {
"total": total,
"contacts": contacts,
"limit": limit,
"offset": offset
}
except Exception as e:
logger.error(f"Failed to get contacts: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/contacts/{contact_id}")
async def get_contact(contact_id: int):
"""Get a single contact by ID"""
try:
query = """
SELECT
id, first_name, last_name, email, phone, mobile,
title, department, is_active, user_company,
created_at, updated_at
FROM contacts
WHERE id = %s
"""
contacts = execute_query(query, (contact_id,))
if not contacts:
raise HTTPException(status_code=404, detail="Contact not found")
return contacts[0]
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to get contact {contact_id}: {e}")
raise HTTPException(status_code=500, detail=str(e))