"""Placing a source document into a container: a new reference, or one more binding of an existing element.""" from __future__ import annotations from fastapi import APIRouter, Depends from fastapi.responses import JSONResponse from psycopg import Connection from app.access.policy import Ctx from app.api.deps import Principal, get_conn, get_principal from app.api.schemas import ExistingIn, ExternalIn from app.ops import bind_existing_external, create_external, existing_externals router = APIRouter() def _ctx_model(value) -> Ctx | None: return None if value is None else Ctx(value.kind, value.id) def place_external(conn, principal: Principal, body: ExternalIn) -> dict: context = Ctx(body.context.kind, body.context.id) placement = _ctx_model(body.placement) if body.bind_element_id is not None: return bind_existing_external(conn, principal.account_id, principal.scope_id, body.bind_element_id, context, placement, body.chapter_id) return create_external( conn, principal.account_id, principal.scope_id, body.title, body.source, body.external_id, context, placement, body.chapter_id, body.dates.document_on, body.dates.sent_on, body.dates.received_on, body.detail.model_dump(mode="json", exclude_none=True) if body.detail else None, duplicate=body.duplicate, ) @router.post("/api/v1/external-refs/existing") def existing(body: ExistingIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): """Read only: which of these documents are already present around the target. Nothing is written.""" items = [ {"source": item.source, "external_id": item.external_id, "connector_id": str(item.connector_id) if item.connector_id else None} for item in body.items ] result = existing_externals(conn, principal.account_id, Ctx(body.context.kind, body.context.id), _ctx_model(body.placement), items) return JSONResponse(result, headers={"Cache-Control": "no-store"})