"""财务数据路由: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.company import Company from app.models.financial_data import FinancialData from app.models.user import User from app.schemas.common import ApiResponse, success from app.services.financial_validator import validate_financial_data router = APIRouter(prefix="/financial", tags=["financial"]) @router.get("", response_model=ApiResponse[list]) async def list_financial_data( company_id: str = Query(...), db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user), ): """获取企业财务数据列表。""" result = await db.execute( select(FinancialData) .join(Company, FinancialData.company_id == Company.id) .where(Company.tenant_id == user.tenant_id, FinancialData.company_id == company_id) .order_by(FinancialData.period_year.desc(), FinancialData.period_month.desc()) ) items = result.scalars().all() return success(data=[ { "id": str(i.id), "company_id": str(i.company_id), "period_year": i.period_year, "period_month": i.period_month, "statement_type": i.statement_type, "data_json": i.data_json, "credibility_score": i.credibility_score, "validation_result": i.validation_result, } for i in items ]) @router.post("", response_model=ApiResponse[dict], status_code=status.HTTP_201_CREATED) async def create_financial_data( req: dict, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user), ): """创建财务数据并自动校验。""" company_id = req.get("company_id") company_result = await db.execute( select(Company).where(Company.id == 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="企业不存在") fd = FinancialData( company_id=company_id, period_year=req.get("period_year"), period_month=req.get("period_month"), statement_type=req.get("statement_type", "balance_sheet"), data_json=req.get("data_json"), source=req.get("source"), ) validation = await validate_financial_data(db, company_id, fd.period_year, fd.period_month) fd.credibility_score = validation["credibility_score"] fd.validation_result = validation db.add(fd) await db.flush() return success(data={"id": str(fd.id), "credibility_score": fd.credibility_score, "validation_result": validation}, message="创建成功") @router.get("/validate", response_model=ApiResponse[dict]) async def validate_financial( company_id: str = Query(...), period_year: int = Query(...), period_month: int = Query(...), db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user), ): """校验财务数据。""" result = await validate_financial_data(db, company_id, period_year, period_month) return success(data=result)