2026-06-29 00:44:34 +02:00
|
|
|
"""Company routes — full CRUD, FTS search, filter, pagination, export, N:M, emails."""
|
2026-06-29 00:10:10 +02:00
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import uuid
|
|
|
|
|
|
2026-06-29 00:44:34 +02:00
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
2026-06-29 00:10:10 +02:00
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
|
|
2026-06-29 00:44:34 +02:00
|
|
|
from app.core.auth import check_permission
|
2026-06-29 00:10:10 +02:00
|
|
|
from app.core.db import get_db
|
2026-06-29 00:44:34 +02:00
|
|
|
from app.deps import get_current_user
|
|
|
|
|
from app.schemas.company import CompanyCreate, CompanyUpdate
|
|
|
|
|
from app.services import company_service
|
2026-06-29 00:10:10 +02:00
|
|
|
|
|
|
|
|
router = APIRouter(prefix="/api/v1/companies", tags=["companies"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.get("")
|
|
|
|
|
async def list_companies(
|
2026-06-29 00:44:34 +02:00
|
|
|
page: int = Query(1, ge=1),
|
|
|
|
|
page_size: int = Query(20, ge=1, le=100),
|
|
|
|
|
search: str | None = Query(None),
|
|
|
|
|
industry: str | None = Query(None),
|
|
|
|
|
sort_by: str = Query("name"),
|
|
|
|
|
sort_order: str = Query("asc", pattern="^(asc|desc)$"),
|
2026-06-29 00:10:10 +02:00
|
|
|
db: AsyncSession = Depends(get_db),
|
|
|
|
|
current_user: dict = Depends(get_current_user),
|
|
|
|
|
):
|
2026-06-29 00:44:34 +02:00
|
|
|
"""List companies with pagination, FTS search, industry filter, and sorting."""
|
2026-06-29 00:10:10 +02:00
|
|
|
tenant_id = uuid.UUID(current_user["tenant_id"])
|
2026-06-29 00:44:34 +02:00
|
|
|
result = await company_service.list_companies(
|
2026-06-29 17:43:56 +02:00
|
|
|
db,
|
|
|
|
|
tenant_id,
|
|
|
|
|
page=page,
|
|
|
|
|
page_size=page_size,
|
|
|
|
|
search=search,
|
|
|
|
|
industry=industry,
|
|
|
|
|
sort_by=sort_by,
|
|
|
|
|
sort_order=sort_order,
|
2026-06-29 00:10:10 +02:00
|
|
|
)
|
2026-06-29 00:44:34 +02:00
|
|
|
return result
|
2026-06-29 00:10:10 +02:00
|
|
|
|
|
|
|
|
|
2026-06-29 00:44:34 +02:00
|
|
|
@router.post("", status_code=status.HTTP_201_CREATED)
|
2026-06-29 00:10:10 +02:00
|
|
|
async def create_company(
|
|
|
|
|
body: CompanyCreate,
|
|
|
|
|
db: AsyncSession = Depends(get_db),
|
|
|
|
|
current_user: dict = Depends(get_current_user),
|
|
|
|
|
):
|
|
|
|
|
"""Create a company. Requires write permission."""
|
|
|
|
|
tenant_id = uuid.UUID(current_user["tenant_id"])
|
|
|
|
|
user_id = uuid.UUID(current_user["user_id"])
|
|
|
|
|
role = current_user.get("role", "viewer")
|
|
|
|
|
|
|
|
|
|
if not check_permission(role, "companies", "create"):
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
|
|
|
detail={"detail": "Insufficient permissions", "code": "forbidden"},
|
|
|
|
|
)
|
|
|
|
|
|
2026-06-29 00:44:34 +02:00
|
|
|
data = body.model_dump()
|
|
|
|
|
return await company_service.create_company(db, tenant_id, user_id, data)
|
2026-06-29 00:10:10 +02:00
|
|
|
|
|
|
|
|
|
2026-06-29 00:44:34 +02:00
|
|
|
@router.get("/export")
|
|
|
|
|
async def export_companies(
|
|
|
|
|
format: str = Query("csv", pattern="^(csv|xlsx)$"),
|
|
|
|
|
industry: str | None = Query(None),
|
|
|
|
|
search: str | None = Query(None),
|
|
|
|
|
db: AsyncSession = Depends(get_db),
|
|
|
|
|
current_user: dict = Depends(get_current_user),
|
|
|
|
|
):
|
|
|
|
|
"""Export companies as CSV or XLSX."""
|
|
|
|
|
tenant_id = uuid.UUID(current_user["tenant_id"])
|
|
|
|
|
|
|
|
|
|
if format == "csv":
|
|
|
|
|
csv_data = await company_service.export_companies_csv(
|
2026-06-29 17:43:56 +02:00
|
|
|
db,
|
|
|
|
|
tenant_id,
|
|
|
|
|
industry=industry,
|
|
|
|
|
search=search,
|
2026-06-29 00:44:34 +02:00
|
|
|
)
|
|
|
|
|
return Response(
|
|
|
|
|
content=csv_data,
|
|
|
|
|
media_type="text/csv",
|
|
|
|
|
headers={"Content-Disposition": "attachment; filename=companies.csv"},
|
|
|
|
|
)
|
|
|
|
|
elif format == "xlsx":
|
|
|
|
|
xlsx_data = await company_service.export_companies_xlsx(
|
2026-06-29 17:43:56 +02:00
|
|
|
db,
|
|
|
|
|
tenant_id,
|
|
|
|
|
industry=industry,
|
|
|
|
|
search=search,
|
2026-06-29 00:44:34 +02:00
|
|
|
)
|
|
|
|
|
return Response(
|
|
|
|
|
content=xlsx_data,
|
|
|
|
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
|
|
|
headers={"Content-Disposition": "attachment; filename=companies.xlsx"},
|
|
|
|
|
)
|
|
|
|
|
raise HTTPException(400, detail={"detail": "Invalid format", "code": "invalid_format"})
|
2026-06-29 00:10:10 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.get("/{company_id}")
|
|
|
|
|
async def get_company(
|
|
|
|
|
company_id: str,
|
|
|
|
|
db: AsyncSession = Depends(get_db),
|
|
|
|
|
current_user: dict = Depends(get_current_user),
|
|
|
|
|
):
|
2026-06-29 00:44:34 +02:00
|
|
|
"""Get a single company with contacts array. Cross-tenant returns 404."""
|
2026-06-29 00:10:10 +02:00
|
|
|
tenant_id = uuid.UUID(current_user["tenant_id"])
|
|
|
|
|
try:
|
|
|
|
|
cid = uuid.UUID(company_id)
|
|
|
|
|
except ValueError:
|
2026-06-29 17:43:56 +02:00
|
|
|
raise HTTPException(
|
|
|
|
|
400, detail={"detail": "Invalid company_id", "code": "invalid_id"}
|
|
|
|
|
) from None
|
2026-06-29 00:10:10 +02:00
|
|
|
|
2026-06-29 00:44:34 +02:00
|
|
|
data = await company_service.get_company_detail(db, tenant_id, cid)
|
|
|
|
|
if data is None:
|
2026-06-29 00:10:10 +02:00
|
|
|
raise HTTPException(404, detail={"detail": "Company not found", "code": "not_found"})
|
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
|
|
2026-06-29 00:44:34 +02:00
|
|
|
@router.put("/{company_id}")
|
2026-06-29 00:10:10 +02:00
|
|
|
async def update_company(
|
|
|
|
|
company_id: str,
|
2026-06-29 00:44:34 +02:00
|
|
|
body: CompanyUpdate,
|
2026-06-29 00:10:10 +02:00
|
|
|
db: AsyncSession = Depends(get_db),
|
|
|
|
|
current_user: dict = Depends(get_current_user),
|
|
|
|
|
):
|
2026-06-29 00:44:34 +02:00
|
|
|
"""Update a company (full PUT)."""
|
2026-06-29 00:10:10 +02:00
|
|
|
tenant_id = uuid.UUID(current_user["tenant_id"])
|
|
|
|
|
user_id = uuid.UUID(current_user["user_id"])
|
|
|
|
|
role = current_user.get("role", "viewer")
|
|
|
|
|
|
|
|
|
|
if not check_permission(role, "companies", "update"):
|
|
|
|
|
raise HTTPException(403, detail={"detail": "Insufficient permissions", "code": "forbidden"})
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
cid = uuid.UUID(company_id)
|
|
|
|
|
except ValueError:
|
2026-06-29 17:43:56 +02:00
|
|
|
raise HTTPException(
|
|
|
|
|
400, detail={"detail": "Invalid company_id", "code": "invalid_id"}
|
|
|
|
|
) from None
|
2026-06-29 00:10:10 +02:00
|
|
|
|
2026-06-29 00:44:34 +02:00
|
|
|
data = body.model_dump(exclude_unset=True)
|
|
|
|
|
result = await company_service.update_company(db, tenant_id, user_id, cid, data)
|
|
|
|
|
if result is None:
|
2026-06-29 00:10:10 +02:00
|
|
|
raise HTTPException(404, detail={"detail": "Company not found", "code": "not_found"})
|
2026-06-29 00:44:34 +02:00
|
|
|
return result
|
2026-06-29 00:10:10 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.delete("/{company_id}")
|
|
|
|
|
async def delete_company(
|
|
|
|
|
company_id: str,
|
2026-06-29 00:44:34 +02:00
|
|
|
cascade: bool = Query(False),
|
2026-06-29 00:10:10 +02:00
|
|
|
db: AsyncSession = Depends(get_db),
|
|
|
|
|
current_user: dict = Depends(get_current_user),
|
|
|
|
|
):
|
2026-06-29 00:44:34 +02:00
|
|
|
"""Soft-delete a company. Use cascade=true to also delete N:M links."""
|
2026-06-29 00:10:10 +02:00
|
|
|
tenant_id = uuid.UUID(current_user["tenant_id"])
|
|
|
|
|
user_id = uuid.UUID(current_user["user_id"])
|
|
|
|
|
role = current_user.get("role", "viewer")
|
|
|
|
|
|
|
|
|
|
if not check_permission(role, "companies", "delete"):
|
|
|
|
|
raise HTTPException(403, detail={"detail": "Insufficient permissions", "code": "forbidden"})
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
cid = uuid.UUID(company_id)
|
|
|
|
|
except ValueError:
|
2026-06-29 17:43:56 +02:00
|
|
|
raise HTTPException(
|
|
|
|
|
400, detail={"detail": "Invalid company_id", "code": "invalid_id"}
|
|
|
|
|
) from None
|
2026-06-29 00:10:10 +02:00
|
|
|
|
2026-06-29 17:43:56 +02:00
|
|
|
deleted = await company_service.soft_delete_company(
|
|
|
|
|
db, tenant_id, user_id, cid, cascade=cascade
|
|
|
|
|
)
|
2026-06-29 00:44:34 +02:00
|
|
|
if not deleted:
|
2026-06-29 00:10:10 +02:00
|
|
|
raise HTTPException(404, detail={"detail": "Company not found", "code": "not_found"})
|
|
|
|
|
|
2026-06-29 00:44:34 +02:00
|
|
|
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
|
|
|
|
2026-06-29 00:10:10 +02:00
|
|
|
|
2026-06-29 00:44:34 +02:00
|
|
|
@router.post("/{company_id}/contacts/{contact_id}")
|
|
|
|
|
async def link_company_contact(
|
|
|
|
|
company_id: str,
|
|
|
|
|
contact_id: str,
|
|
|
|
|
db: AsyncSession = Depends(get_db),
|
|
|
|
|
current_user: dict = Depends(get_current_user),
|
|
|
|
|
):
|
|
|
|
|
"""Link a contact to a company (N:M)."""
|
|
|
|
|
tenant_id = uuid.UUID(current_user["tenant_id"])
|
|
|
|
|
user_id = uuid.UUID(current_user["user_id"])
|
|
|
|
|
role = current_user.get("role", "viewer")
|
|
|
|
|
|
|
|
|
|
if not check_permission(role, "companies", "update"):
|
|
|
|
|
raise HTTPException(403, detail={"detail": "Insufficient permissions", "code": "forbidden"})
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
comp_id = uuid.UUID(company_id)
|
|
|
|
|
cont_id = uuid.UUID(contact_id)
|
|
|
|
|
except ValueError:
|
2026-06-29 17:43:56 +02:00
|
|
|
raise HTTPException(400, detail={"detail": "Invalid ID", "code": "invalid_id"}) from None
|
2026-06-29 00:44:34 +02:00
|
|
|
|
|
|
|
|
result = await company_service.link_contact(db, tenant_id, user_id, comp_id, cont_id)
|
|
|
|
|
if result is None:
|
2026-06-29 17:43:56 +02:00
|
|
|
raise HTTPException(
|
|
|
|
|
404, detail={"detail": "Company or contact not found", "code": "not_found"}
|
|
|
|
|
)
|
2026-06-29 00:44:34 +02:00
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.delete("/{company_id}/contacts/{contact_id}")
|
|
|
|
|
async def unlink_company_contact(
|
|
|
|
|
company_id: str,
|
|
|
|
|
contact_id: str,
|
|
|
|
|
db: AsyncSession = Depends(get_db),
|
|
|
|
|
current_user: dict = Depends(get_current_user),
|
|
|
|
|
):
|
|
|
|
|
"""Unlink a contact from a company (N:M)."""
|
|
|
|
|
tenant_id = uuid.UUID(current_user["tenant_id"])
|
|
|
|
|
user_id = uuid.UUID(current_user["user_id"])
|
|
|
|
|
role = current_user.get("role", "viewer")
|
|
|
|
|
|
|
|
|
|
if not check_permission(role, "companies", "update"):
|
|
|
|
|
raise HTTPException(403, detail={"detail": "Insufficient permissions", "code": "forbidden"})
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
comp_id = uuid.UUID(company_id)
|
|
|
|
|
cont_id = uuid.UUID(contact_id)
|
|
|
|
|
except ValueError:
|
2026-06-29 17:43:56 +02:00
|
|
|
raise HTTPException(400, detail={"detail": "Invalid ID", "code": "invalid_id"}) from None
|
2026-06-29 00:44:34 +02:00
|
|
|
|
|
|
|
|
unlinked = await company_service.unlink_contact(db, tenant_id, user_id, comp_id, cont_id)
|
|
|
|
|
if not unlinked:
|
|
|
|
|
raise HTTPException(404, detail={"detail": "Link not found", "code": "not_found"})
|
2026-06-29 00:10:10 +02:00
|
|
|
|
|
|
|
|
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
|
|
|
|
|
|
|
|
|
2026-06-29 00:44:34 +02:00
|
|
|
@router.get("/{company_id}/emails")
|
|
|
|
|
async def get_company_emails(
|
|
|
|
|
company_id: str,
|
|
|
|
|
db: AsyncSession = Depends(get_db),
|
|
|
|
|
current_user: dict = Depends(get_current_user),
|
|
|
|
|
):
|
|
|
|
|
"""Get emails for a company (mail plugin inactive — returns empty array)."""
|
|
|
|
|
tenant_id = uuid.UUID(current_user["tenant_id"])
|
|
|
|
|
try:
|
|
|
|
|
cid = uuid.UUID(company_id)
|
|
|
|
|
except ValueError:
|
2026-06-29 17:43:56 +02:00
|
|
|
raise HTTPException(
|
|
|
|
|
400, detail={"detail": "Invalid company_id", "code": "invalid_id"}
|
|
|
|
|
) from None
|
2026-06-29 00:44:34 +02:00
|
|
|
|
|
|
|
|
# Verify company exists
|
|
|
|
|
from sqlalchemy import select
|
2026-06-29 17:43:56 +02:00
|
|
|
|
2026-06-29 00:44:34 +02:00
|
|
|
from app.models.company import Company
|
2026-06-29 17:43:56 +02:00
|
|
|
|
2026-06-29 00:44:34 +02:00
|
|
|
q = select(Company).where(
|
|
|
|
|
Company.id == cid,
|
|
|
|
|
Company.tenant_id == tenant_id,
|
|
|
|
|
Company.deleted_at.is_(None),
|
|
|
|
|
)
|
|
|
|
|
result = await db.execute(q)
|
|
|
|
|
if result.scalar_one_or_none() is None:
|
|
|
|
|
raise HTTPException(404, detail={"detail": "Company not found", "code": "not_found"})
|
|
|
|
|
|
|
|
|
|
return []
|