Fix: Tilføjet company_count og company_names til contacts API med JOIN

This commit is contained in:
Christian 2025-12-22 15:48:21 +01:00
parent ba0a2fd160
commit 9fe17e7f85

View File

@ -12,6 +12,54 @@ logger = logging.getLogger(__name__)
router = APIRouter()
@router.get("/contacts-debug")
async def debug_contacts():
"""Debug endpoint: Check contact-company links"""
try:
# Count links
links = execute_query("SELECT COUNT(*) as total FROM contact_companies")
# Get sample with links
sample = execute_query("""
SELECT
c.id, c.first_name, c.last_name,
COUNT(cc.customer_id) as company_count,
ARRAY_AGG(cu.name) as company_names
FROM contacts c
LEFT JOIN contact_companies cc ON c.id = cc.contact_id
LEFT JOIN customers cu ON cc.customer_id = cu.id
GROUP BY c.id, c.first_name, c.last_name
HAVING COUNT(cc.customer_id) > 0
LIMIT 10
""")
# Test the actual query used in get_contacts
test_query = """
SELECT
c.id, c.first_name, c.last_name,
COUNT(DISTINCT cc.customer_id) as company_count,
ARRAY_AGG(DISTINCT cu.name ORDER BY cu.name) FILTER (WHERE cu.name IS NOT NULL) as company_names
FROM contacts c
LEFT JOIN contact_companies cc ON c.id = cc.contact_id
LEFT JOIN customers cu ON cc.customer_id = cu.id
GROUP BY c.id, c.first_name, c.last_name
ORDER BY c.last_name, c.first_name
LIMIT 10
"""
test_result = execute_query(test_query)
return {
"total_links": links[0]['total'] if links else 0,
"sample_contacts_with_companies": sample or [],
"test_query_result": test_result or [],
"note": "If company_count is 0, the JOIN might not be working"
}
except Exception as e:
logger.error(f"Debug failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
@router.get("/contacts")
async def get_contacts(
search: Optional[str] = None,
@ -40,14 +88,20 @@ async def get_contacts(
count_result = execute_query(count_query, tuple(params))
total = count_result[0]['count'] if count_result else 0
# Get contacts
# Get contacts with company info
query = f"""
SELECT
id, first_name, last_name, email, phone, mobile,
title, department, is_active, created_at, updated_at
FROM contacts
c.id, c.first_name, c.last_name, c.email, c.phone, c.mobile,
c.title, c.department, c.is_active, c.created_at, c.updated_at,
COUNT(DISTINCT cc.customer_id) as company_count,
ARRAY_AGG(DISTINCT cu.name ORDER BY cu.name) FILTER (WHERE cu.name IS NOT NULL) as company_names
FROM contacts c
LEFT JOIN contact_companies cc ON c.id = cc.contact_id
LEFT JOIN customers cu ON cc.customer_id = cu.id
{where_sql}
ORDER BY first_name, last_name
GROUP BY c.id, c.first_name, c.last_name, c.email, c.phone, c.mobile,
c.title, c.department, c.is_active, c.created_at, c.updated_at
ORDER BY c.first_name, c.last_name
LIMIT %s OFFSET %s
"""
params.extend([limit, offset])