T11: tags plugin + permissions plugin + entity links backend — 68 tests, 66.61% coverage

This commit is contained in:
leocrm-bot
2026-06-29 14:01:24 +02:00
parent 700b7a71ad
commit 5d1850768a
26 changed files with 2863 additions and 7 deletions
@@ -0,0 +1,5 @@
"""Entity Links builtin plugin."""
from app.plugins.builtins.entity_links.plugin import EntityLinksPlugin
__all__ = ["EntityLinksPlugin"]
@@ -0,0 +1,14 @@
-- Entity Links plugin initial migration: creates entity_links table
CREATE TABLE IF NOT EXISTS entity_links (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL,
file_id UUID NOT NULL,
entity_type VARCHAR(20) NOT NULL,
entity_id UUID NOT NULL,
created_by UUID,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT uq_entity_links_file_entity UNIQUE (tenant_id, file_id, entity_type, entity_id)
);
CREATE INDEX IF NOT EXISTS ix_entity_links_file ON entity_links(tenant_id, file_id);
CREATE INDEX IF NOT EXISTS ix_entity_links_entity ON entity_links(tenant_id, entity_type, entity_id);
@@ -0,0 +1,35 @@
"""EntityLink model for the Entity Links plugin."""
from __future__ import annotations
import uuid
from sqlalchemy import String, ForeignKey, Index, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column
from app.core.db import Base, TenantMixin
class EntityLink(Base, TenantMixin):
"""N:M link between files/folders and companies/contacts."""
__tablename__ = "entity_links"
__table_args__ = (
UniqueConstraint(
"tenant_id", "file_id", "entity_type", "entity_id",
name="uq_entity_links_file_entity",
),
Index("ix_entity_links_file", "tenant_id", "file_id"),
Index("ix_entity_links_entity", "tenant_id", "entity_type", "entity_id"),
)
id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4
)
file_id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), nullable=False)
entity_type: Mapped[str] = mapped_column(String(20), nullable=False)
entity_id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), nullable=False)
created_by: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True), nullable=True
)
@@ -0,0 +1,86 @@
"""Entity Links plugin — link files to companies/contacts, reverse links, event cleanup."""
from __future__ import annotations
from typing import Any
from app.plugins.base import BasePlugin
from app.plugins.manifest import PluginManifest, PluginRouteDef
class EntityLinksPlugin(BasePlugin):
"""Entity Links plugin for N:M file-to-entity links with event-driven cleanup."""
manifest = PluginManifest(
name="entity_links",
version="1.0.0",
display_name="Entity Links",
description="Link files to companies/contacts (N:M), reverse links, event cleanup on deletion.",
dependencies=[],
routes=[
PluginRouteDef(
path="/api/v1/dms",
module="app.plugins.builtins.entity_links.routes",
router_attr="router",
),
PluginRouteDef(
path="/api/v1/companies",
module="app.plugins.builtins.entity_links.routes",
router_attr="company_router",
),
PluginRouteDef(
path="/api/v1/contacts",
module="app.plugins.builtins.entity_links.routes",
router_attr="contact_router",
),
],
events=["company.deleted", "contact.deleted"],
migrations=["0001_initial.sql"],
permissions=[],
)
async def on_company_deleted(self, payload: dict[str, Any]) -> None:
"""Handle company.deleted event — remove all EntityLink rows for that company."""
from sqlalchemy import delete
from app.core.db import get_session_factory
from app.plugins.builtins.entity_links.models import EntityLink
entity_id = payload.get("entity_id") or payload.get("company_id")
tenant_id = payload.get("tenant_id")
if entity_id is None or tenant_id is None:
return
import uuid as _uuid
factory = get_session_factory()
async with factory() as session:
await session.execute(
delete(EntityLink).where(
EntityLink.tenant_id == _uuid.UUID(tenant_id),
EntityLink.entity_type == "company",
EntityLink.entity_id == _uuid.UUID(str(entity_id)),
)
)
await session.commit()
async def on_contact_deleted(self, payload: dict[str, Any]) -> None:
"""Handle contact.deleted event — remove all EntityLink rows for that contact."""
from sqlalchemy import delete
from app.core.db import get_session_factory
from app.plugins.builtins.entity_links.models import EntityLink
entity_id = payload.get("entity_id") or payload.get("contact_id")
tenant_id = payload.get("tenant_id")
if entity_id is None or tenant_id is None:
return
import uuid as _uuid
factory = get_session_factory()
async with factory() as session:
await session.execute(
delete(EntityLink).where(
EntityLink.tenant_id == _uuid.UUID(tenant_id),
EntityLink.entity_type == "contact",
EntityLink.entity_id == _uuid.UUID(str(entity_id)),
)
)
await session.commit()
+194
View File
@@ -0,0 +1,194 @@
"""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, delete
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.db import get_db
from app.deps import get_current_user
from app.plugins.builtins.entity_links.models import EntityLink
from app.plugins.builtins.entity_links.schemas import EntityLinkRequest
router = APIRouter(prefix="/api/v1/dms", tags=["entity-links"])
company_router = APIRouter(prefix="/api/v1/companies", tags=["entity-links"])
contact_router = APIRouter(prefix="/api/v1/contacts", tags=["entity-links"])
VALID_ENTITY_TYPES = {"company", "contact"}
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"})
@router.post("/files/{file_id}/link")
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 company or 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 body.entity_type not in VALID_ENTITY_TYPES:
raise HTTPException(400, detail={"detail": "Invalid entity_type", "code": "invalid_entity_type"})
# 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)
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")
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
]
@company_router.get("/{company_id}/files")
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
]
@contact_router.get("/{contact_id}/files")
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
]
@@ -0,0 +1,22 @@
"""Pydantic schemas for the Entity Links plugin."""
from __future__ import annotations
from pydantic import BaseModel, Field
class EntityLinkRequest(BaseModel):
entity_type: str = Field(..., pattern="^(company|contact)$")
entity_id: str
class EntityLinkResponse(BaseModel):
id: str
file_id: str
entity_type: str
entity_id: str
class FileListResponse(BaseModel):
file_id: str
entity_type: str