"""投资协议路由:CRUD + 条款预警。""" from fastapi import APIRouter, Depends, HTTPException, Query, status from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.core.database import get_db from app.core.dependencies import get_current_user from app.models.agreement import InvestmentAgreement from app.models.company import Company from app.models.user import User from app.schemas.common import ApiResponse, success from app.services.agreement_monitor import check_clause_triggers router = APIRouter(prefix="/agreements", tags=["agreements"]) @router.get("", response_model=ApiResponse[list]) async def list_agreements( company_id: str | None = Query(default=None), db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user), ): """获取投资协议列表。""" query = ( select(InvestmentAgreement) .join(Company, InvestmentAgreement.company_id == Company.id) .where(Company.tenant_id == user.tenant_id) ) if company_id: query = query.where(InvestmentAgreement.company_id == company_id) result = await db.execute(query.order_by(InvestmentAgreement.created_at.desc())) items = result.scalars().all() return success(data=[ { "id": str(i.id), "company_id": str(i.company_id), "title": i.title, "signed_at": i.signed_at.isoformat() if i.signed_at else None, "key_clauses": i.key_clauses, "monitoring_rules": i.monitoring_rules, "status": i.status, } for i in items ]) @router.post("", response_model=ApiResponse[dict], status_code=status.HTTP_201_CREATED) async def create_agreement( req: dict, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user), ): """创建投资协议。""" company_result = await db.execute( select(Company).where(Company.id == req.get("company_id"), Company.tenant_id == user.tenant_id) ) if not company_result.scalar_one_or_none(): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="企业不存在") agreement = InvestmentAgreement( company_id=req.get("company_id"), title=req.get("title"), signed_at=req.get("signed_at"), file_url=req.get("file_url"), key_clauses=req.get("key_clauses"), monitoring_rules=req.get("monitoring_rules"), ) db.add(agreement) await db.flush() return success(data={"id": str(agreement.id)}, message="创建成功") @router.get("/{agreement_id}/alerts", response_model=ApiResponse[list]) async def get_clause_alerts( agreement_id: str, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user), ): """获取协议条款预警。""" result = await db.execute( select(InvestmentAgreement) .join(Company, InvestmentAgreement.company_id == Company.id) .where(InvestmentAgreement.id == agreement_id, Company.tenant_id == user.tenant_id) ) agreement = result.scalar_one_or_none() if not agreement: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="协议不存在") alerts = await check_clause_triggers(db, str(agreement.company_id)) return success(data=alerts)