import uuid from typing import Sequence from sqlalchemy import select, update as sa_update from sqlalchemy.ext.asyncio import AsyncSession from app.models.document import Document async def create(db: AsyncSession, doc: Document, *, commit: bool = True) -> Document: db.add(doc) if commit: await db.commit() await db.refresh(doc) return doc async def get(db: AsyncSession, document_id: uuid.UUID) -> Document | None: result = await db.execute(select(Document).where(Document.id == document_id)) return result.scalar_one_or_none() async def get_by_trial_doc_no(db: AsyncSession, trial_id: uuid.UUID, doc_no: str) -> Document | None: result = await db.execute(select(Document).where(Document.trial_id == trial_id, Document.doc_no == doc_no)) return result.scalar_one_or_none() async def list_documents( db: AsyncSession, *, trial_id: uuid.UUID, site_id: uuid.UUID | None = None, doc_type: str | None = None, status: str | None = None, scope_type: str | None = None, cra_site_ids: set[uuid.UUID] | None = None, skip: int = 0, limit: int = 100, ) -> Sequence[Document]: stmt = select(Document).where(Document.trial_id == trial_id) if cra_site_ids is not None: if not cra_site_ids: stmt = stmt.where(Document.scope_type == "GLOBAL") else: stmt = stmt.where((Document.scope_type == "GLOBAL") | (Document.site_id.in_(cra_site_ids))) if scope_type: stmt = stmt.where(Document.scope_type == scope_type) if doc_type: stmt = stmt.where(Document.doc_type == doc_type) if status: stmt = stmt.where(Document.status == status) if site_id: stmt = stmt.where(Document.site_id == site_id) stmt = stmt.order_by(Document.updated_at.desc()).offset(skip).limit(limit) result = await db.execute(stmt) return result.scalars().all() async def update(db: AsyncSession, document_id: uuid.UUID, values: dict, *, commit: bool = True) -> None: if values: await db.execute( sa_update(Document) .where(Document.id == document_id) .values(**values) ) if commit: await db.commit()