2025-12-17 16:38:08 +01:00
|
|
|
"""
|
|
|
|
|
Contact API Router - Simplified (Read-Only)
|
|
|
|
|
Only GET endpoints for now
|
|
|
|
|
"""
|
|
|
|
|
|
2026-01-10 21:09:29 +01:00
|
|
|
from fastapi import APIRouter, HTTPException, Query, Body, status
|
2025-12-17 16:38:08 +01:00
|
|
|
from typing import Optional
|
2026-01-10 21:09:29 +01:00
|
|
|
from pydantic import BaseModel, Field
|
|
|
|
|
from app.core.database import execute_query, execute_insert
|
2025-12-17 16:38:08 +01:00
|
|
|
import logging
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
|
|
|
|
|
2026-01-10 21:09:29 +01:00
|
|
|
class ContactCreate(BaseModel):
|
|
|
|
|
"""Schema for creating a contact"""
|
|
|
|
|
first_name: str
|
|
|
|
|
last_name: str = ""
|
|
|
|
|
email: Optional[str] = None
|
|
|
|
|
phone: Optional[str] = None
|
|
|
|
|
title: Optional[str] = None
|
|
|
|
|
company_id: Optional[int] = None
|
|
|
|
|
|
|
|
|
|
|
2026-02-03 15:37:16 +01:00
|
|
|
class ContactCompanyLink(BaseModel):
|
|
|
|
|
customer_id: int
|
|
|
|
|
is_primary: bool = True
|
|
|
|
|
role: Optional[str] = None
|
|
|
|
|
|
|
|
|
|
|
2026-01-10 21:09:29 +01:00
|
|
|
|
2025-12-22 15:48:21 +01:00
|
|
|
@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))
|
|
|
|
|
|
|
|
|
|
|
2025-12-17 16:38:08 +01:00
|
|
|
@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:
|
2025-12-22 16:04:49 +01:00
|
|
|
where_clauses.append("(c.first_name ILIKE %s OR c.last_name ILIKE %s OR c.email ILIKE %s)")
|
2025-12-17 16:38:08 +01:00
|
|
|
params.extend([f"%{search}%", f"%{search}%", f"%{search}%"])
|
|
|
|
|
|
|
|
|
|
if is_active is not None:
|
2025-12-22 16:04:49 +01:00
|
|
|
where_clauses.append("c.is_active = %s")
|
2025-12-17 16:38:08 +01:00
|
|
|
params.append(is_active)
|
|
|
|
|
|
|
|
|
|
where_sql = "WHERE " + " AND ".join(where_clauses) if where_clauses else ""
|
|
|
|
|
|
2025-12-22 16:04:49 +01:00
|
|
|
# Count total (needs alias c for consistency)
|
|
|
|
|
count_query = f"SELECT COUNT(*) as count FROM contacts c {where_sql}"
|
2025-12-17 16:38:08 +01:00
|
|
|
count_result = execute_query(count_query, tuple(params))
|
|
|
|
|
total = count_result[0]['count'] if count_result else 0
|
|
|
|
|
|
2025-12-22 15:48:21 +01:00
|
|
|
# Get contacts with company info
|
2025-12-17 16:38:08 +01:00
|
|
|
query = f"""
|
|
|
|
|
SELECT
|
2025-12-22 15:48:21 +01:00
|
|
|
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
|
2025-12-17 16:38:08 +01:00
|
|
|
{where_sql}
|
2025-12-22 15:48:21 +01:00
|
|
|
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
|
2025-12-24 10:34:13 +01:00
|
|
|
ORDER BY company_count DESC, c.last_name, c.first_name
|
2025-12-17 16:38:08 +01:00
|
|
|
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))
|
|
|
|
|
|
|
|
|
|
|
2026-01-10 21:09:29 +01:00
|
|
|
@router.post("/contacts", status_code=status.HTTP_201_CREATED)
|
|
|
|
|
async def create_contact(contact: ContactCreate):
|
|
|
|
|
"""
|
|
|
|
|
Create a new basic contact
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
# Check if email exists
|
|
|
|
|
if contact.email:
|
|
|
|
|
existing = execute_query(
|
|
|
|
|
"SELECT id FROM contacts WHERE email = %s",
|
|
|
|
|
(contact.email,)
|
|
|
|
|
)
|
|
|
|
|
if existing:
|
|
|
|
|
# Return existing contact if found? Or error?
|
|
|
|
|
# For now, let's error to be safe, or just return it?
|
|
|
|
|
# User prompted "Smart Create", implies if it exists, use it?
|
|
|
|
|
# But safer to say "Email already exists"
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
insert_query = """
|
|
|
|
|
INSERT INTO contacts (first_name, last_name, email, phone, title, is_active)
|
|
|
|
|
VALUES (%s, %s, %s, %s, %s, true)
|
|
|
|
|
RETURNING id
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
contact_id = execute_insert(
|
|
|
|
|
insert_query,
|
|
|
|
|
(contact.first_name, contact.last_name, contact.email, contact.phone, contact.title)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# Link to company if provided
|
|
|
|
|
if contact.company_id:
|
|
|
|
|
try:
|
|
|
|
|
link_query = """
|
|
|
|
|
INSERT INTO contact_companies (contact_id, customer_id, is_primary, role)
|
|
|
|
|
VALUES (%s, %s, true, 'primary')
|
2026-02-03 15:37:16 +01:00
|
|
|
ON CONFLICT (contact_id, customer_id)
|
|
|
|
|
DO UPDATE SET is_primary = EXCLUDED.is_primary, role = EXCLUDED.role
|
|
|
|
|
RETURNING id
|
2026-01-10 21:09:29 +01:00
|
|
|
"""
|
|
|
|
|
execute_insert(link_query, (contact_id, contact.company_id))
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"Failed to link new contact {contact_id} to company {contact.company_id}: {e}")
|
|
|
|
|
# Don't fail the whole request, just log it
|
|
|
|
|
|
|
|
|
|
return await get_contact(contact_id)
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"Failed to create contact: {e}")
|
|
|
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
|
|
|
|
|
2025-12-17 16:38:08 +01:00
|
|
|
@router.get("/contacts/{contact_id}")
|
|
|
|
|
async def get_contact(contact_id: int):
|
2025-12-22 16:40:49 +01:00
|
|
|
"""Get a single contact by ID with linked companies"""
|
2025-12-17 16:38:08 +01:00
|
|
|
try:
|
2025-12-22 16:40:49 +01:00
|
|
|
# Get contact info
|
2025-12-17 16:38:08 +01:00
|
|
|
query = """
|
|
|
|
|
SELECT
|
|
|
|
|
id, first_name, last_name, email, phone, mobile,
|
2025-12-22 16:40:49 +01:00
|
|
|
title, department, is_active, user_company, vtiger_id,
|
2025-12-17 16:38:08 +01:00
|
|
|
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")
|
|
|
|
|
|
2025-12-22 16:40:49 +01:00
|
|
|
contact = contacts[0]
|
|
|
|
|
|
|
|
|
|
# Get linked companies
|
|
|
|
|
companies_query = """
|
|
|
|
|
SELECT
|
|
|
|
|
cu.id, cu.name, cu.cvr_number,
|
|
|
|
|
cc.is_primary, cc.role, cc.notes
|
|
|
|
|
FROM contact_companies cc
|
|
|
|
|
JOIN customers cu ON cc.customer_id = cu.id
|
|
|
|
|
WHERE cc.contact_id = %s
|
|
|
|
|
ORDER BY cc.is_primary DESC, cu.name
|
|
|
|
|
"""
|
|
|
|
|
companies = execute_query(companies_query, (contact_id,))
|
|
|
|
|
|
|
|
|
|
contact['companies'] = companies or []
|
|
|
|
|
|
|
|
|
|
return contact
|
2025-12-17 16:38:08 +01:00
|
|
|
|
|
|
|
|
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))
|
2026-02-03 15:37:16 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.post("/contacts/{contact_id}/companies")
|
|
|
|
|
async def link_contact_to_company(contact_id: int, link: ContactCompanyLink):
|
|
|
|
|
"""Link a contact to a company"""
|
|
|
|
|
try:
|
|
|
|
|
# Ensure contact exists
|
|
|
|
|
contact = execute_query("SELECT id FROM contacts WHERE id = %s", (contact_id,))
|
|
|
|
|
if not contact:
|
|
|
|
|
raise HTTPException(status_code=404, detail="Contact not found")
|
|
|
|
|
|
|
|
|
|
# Ensure customer exists
|
|
|
|
|
customer = execute_query("SELECT id FROM customers WHERE id = %s", (link.customer_id,))
|
|
|
|
|
if not customer:
|
|
|
|
|
raise HTTPException(status_code=404, detail="Customer not found")
|
|
|
|
|
|
|
|
|
|
query = """
|
|
|
|
|
INSERT INTO contact_companies (contact_id, customer_id, is_primary, role)
|
|
|
|
|
VALUES (%s, %s, %s, %s)
|
|
|
|
|
ON CONFLICT (contact_id, customer_id)
|
|
|
|
|
DO UPDATE SET is_primary = EXCLUDED.is_primary, role = EXCLUDED.role
|
|
|
|
|
RETURNING id
|
|
|
|
|
"""
|
|
|
|
|
execute_insert(query, (contact_id, link.customer_id, link.is_primary, link.role))
|
|
|
|
|
|
|
|
|
|
return {"message": "Contact linked to company successfully"}
|
|
|
|
|
except HTTPException:
|
|
|
|
|
raise
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"Failed to link contact to company: {e}")
|
|
|
|
|
raise HTTPException(status_code=500, detail=str(e))
|