Files
leocrm/app/plugins/builtins/entity_links/routes.py
T
Agent Zero abbe7a18fc fix(audit): P0-P3 audit fixes — 838 ruff errors → 0, 30 F821 bugs fixed, 118 files changed
- P0: hooks.py 3-tuple fix, trigger_dispatcher Contract, contacts/plugin unregister_actions_by_owner
- P0: 5 test files — check_permission mocks removed, hardcoded DB credential → env var
- P1: attachment_service DmsFile via Contract helper, restore_registry/history_hooks dedup
- P1: mail/plugin restore unregister, mcp_client datetime.now(UTC), saved_views/filters patterns
- P1: ProtectedRoute fail-closed, 13 test assertion fixes (bcrypt, DB-URLs, SECRET_KEYs)
- P2: deprecated notifications → post_system_message (3 files), forgejo Base, report_generator lazy import
- P2: webhooks permissions, deps.py/roles.py plugin perms removed, import_export default
- P2: address/tags/entity_links patterns removed, worker.py Contract-Umgehungen fixed
- P2: 28 frontend TODOs (hardcoded constants, deprecated notification API)
- P3: dead code, duplicates, deprecated imports, private attr, __import__ inline
- P3: 8 frontend TODOs (LucideIcons, inline styles, XSS, i18n)
- ruff: 838 → 0 (612 auto-fix + 246 manual + 27 F821 regression fix)
- F821: 30 → 0 (AutomationDefinition, DmsFile, user_id, Path, Any, String)
- Contract-Umgehungen: 2 neue gefunden (worker.py:169, worker.py:280) und gefixt
2026-08-16 01:17:18 +02:00

213 lines
7.1 KiB
Python

"""Entity Links plugin routes — link files to companies/contacts, reverse links."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Body, Depends, HTTPException, Response, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.db import get_db
from app.deps import get_current_user, require_permission
from app.plugins.builtins.entity_links.models import EntityLink
from app.plugins.builtins.entity_links.schemas import EntityLinkRequest
from app.services.entity_permission_service import check_entity_access
router = APIRouter(prefix="/api/v1/entity-links", tags=["entity-links"])
contact_router = APIRouter(prefix="/api/v1/contacts", tags=["entity-links"])
company_router = APIRouter(prefix="/api/v1/companies", tags=["entity-links"])
# Entity types validated dynamically against ENTITY_MODELS at runtime (P1-13 fix)
def _is_valid_entity_type(entity_type: str) -> bool:
"""Check if entity_type is registered in ENTITY_MODELS."""
from app.services.entity_permission_service import ENTITY_MODELS
return entity_type in ENTITY_MODELS
def _parse_uuid(val: str, field: str) -> uuid.UUID:
try:
return uuid.UUID(val)
except (ValueError, TypeError):
raise HTTPException(
400, detail={"detail": f"Invalid {field}", "code": "invalid_id"}
) from None
@router.post("/files/{file_id}/link", dependencies=[Depends(require_permission("entity_links:write"))])
async def link_file_to_entity(
file_id: str,
body: EntityLinkRequest,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
):
"""Link a file to a contact."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
fid = _parse_uuid(file_id, "file_id")
entity_id = _parse_uuid(body.entity_id, "entity_id")
if not _is_valid_entity_type(body.entity_type):
raise HTTPException(
400, detail={"detail": "Invalid entity_type", "code": "invalid_entity_type"}
)
# Verify user has read access to both the file and the target entity
has_file_access = await check_entity_access(db, tenant_id, user_id, "file", fid, "read")
if not has_file_access:
raise HTTPException(403, detail={"detail": "No access to file", "code": "forbidden"})
has_entity_access = await check_entity_access(db, tenant_id, user_id, body.entity_type, entity_id, "read")
if not has_entity_access:
raise HTTPException(403, detail={"detail": "No access to target entity", "code": "forbidden"})
# Check if link already exists
existing = await db.execute(
select(EntityLink).where(
EntityLink.tenant_id == tenant_id,
EntityLink.file_id == fid,
EntityLink.entity_type == body.entity_type,
EntityLink.entity_id == entity_id,
)
)
existing_link = existing.scalar_one_or_none()
if existing_link is not None:
return {
"id": str(existing_link.id),
"file_id": str(fid),
"entity_type": body.entity_type,
"entity_id": str(entity_id),
"already_linked": True,
}
link = EntityLink(
tenant_id=tenant_id,
file_id=fid,
entity_type=body.entity_type,
entity_id=entity_id,
created_by=user_id,
)
db.add(link)
await db.flush()
return {
"id": str(link.id),
"file_id": str(link.file_id),
"entity_type": link.entity_type,
"entity_id": str(link.entity_id),
"already_linked": False,
}
@router.delete("/files/{file_id}/link", status_code=status.HTTP_204_NO_CONTENT, dependencies=[Depends(require_permission("entity_links:delete"))])
async def unlink_file_from_entity(
file_id: str,
body: EntityLinkRequest = Body(...),
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
):
"""Remove a link between a file and an entity."""
tenant_id = uuid.UUID(current_user["tenant_id"])
fid = _parse_uuid(file_id, "file_id")
entity_id = _parse_uuid(body.entity_id, "entity_id")
result = await db.execute(
select(EntityLink).where(
EntityLink.tenant_id == tenant_id,
EntityLink.file_id == fid,
EntityLink.entity_type == body.entity_type,
EntityLink.entity_id == entity_id,
)
)
link = result.scalar_one_or_none()
if link is None:
raise HTTPException(404, detail={"detail": "Link not found", "code": "not_found"})
await db.delete(link)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.get("/files/{file_id}/links", dependencies=[Depends(require_permission("entity_links:read"))])
async def list_file_links(
file_id: str,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
):
"""List all entities linked to a file."""
tenant_id = uuid.UUID(current_user["tenant_id"])
fid = _parse_uuid(file_id, "file_id")
result = await db.execute(
select(EntityLink).where(
EntityLink.tenant_id == tenant_id,
EntityLink.file_id == fid,
)
)
links = result.scalars().all()
return [
{
"id": str(link.id),
"file_id": str(link.file_id),
"entity_type": link.entity_type,
"entity_id": str(link.entity_id),
}
for link in links
]
@contact_router.get("/{contact_id}/files", dependencies=[Depends(require_permission("entity_links:read"))])
async def list_contact_files(
contact_id: str,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
):
"""List all files linked to a contact (reverse link)."""
tenant_id = uuid.UUID(current_user["tenant_id"])
cid = _parse_uuid(contact_id, "contact_id")
result = await db.execute(
select(EntityLink).where(
EntityLink.tenant_id == tenant_id,
EntityLink.entity_type == "contact",
EntityLink.entity_id == cid,
)
)
links = result.scalars().all()
return [
{
"id": str(link.id),
"file_id": str(link.file_id),
"entity_type": link.entity_type,
"entity_id": str(link.entity_id),
}
for link in links
]
@company_router.get("/{company_id}/files", dependencies=[Depends(require_permission("entity_links:read"))])
async def list_company_files(
company_id: str,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
):
"""List all files linked to a company (reverse link)."""
tenant_id = uuid.UUID(current_user["tenant_id"])
cid = _parse_uuid(company_id, "company_id")
result = await db.execute(
select(EntityLink).where(
EntityLink.tenant_id == tenant_id,
EntityLink.entity_type == "company",
EntityLink.entity_id == cid,
)
)
links = result.scalars().all()
return [
{
"id": str(link.id),
"file_id": str(link.file_id),
"entity_type": link.entity_type,
"entity_id": str(link.entity_id),
}
for link in links
]