"""DATEV export router: create exports, list exports, download CSV.""" import uuid from fastapi import APIRouter, Depends, HTTPException, Query, status from fastapi.responses import Response from sqlalchemy.ext.asyncio import AsyncSession from app.database import get_db from app.dependencies import get_current_user, get_pagination from app.models.user import User from app.schemas.datev import ( DATEVExportCreate, DATEVExportListResponse, DATEVExportResponse, ) from app.services import datev_service router = APIRouter(prefix="/datev", tags=["datev"]) @router.post("/export", response_model=DATEVExportResponse, status_code=status.HTTP_201_CREATED) async def create_export( body: DATEVExportCreate, db: AsyncSession = Depends(get_db), current_user: User = Depends(get_current_user), ): """Create a DATEV export for the given date range. Queries all completed sales within the date range and generates a CSV file. """ export = await datev_service.create_export( db, start_date=body.start_date, end_date=body.end_date, ) return DATEVExportResponse.model_validate(export) @router.get("/exports", response_model=DATEVExportListResponse, status_code=status.HTTP_200_OK) async def list_exports( db: AsyncSession = Depends(get_db), pagination: dict = Depends(get_pagination), current_user: User = Depends(get_current_user), ): """List all DATEV exports with pagination.""" exports, total = await datev_service.list_exports( db, page=pagination["page"], page_size=pagination["page_size"], ) return DATEVExportListResponse( items=[DATEVExportResponse.model_validate(e) for e in exports], total=total, page=pagination["page"], page_size=pagination["page_size"], ) @router.get("/exports/{export_id}/download", status_code=status.HTTP_200_OK) async def download_export( export_id: uuid.UUID, db: AsyncSession = Depends(get_db), current_user: User = Depends(get_current_user), ): """Download a DATEV export as CSV file.""" result = await datev_service.get_export_csv(db, export_id) if result is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail={"error": {"code": "EXPORT_NOT_FOUND", "message": "DATEV export not found"}}, ) filename, csv_bytes = result return Response( content=csv_bytes, media_type="text/csv", headers={"Content-Disposition": f'attachment; filename="{filename}"'}, )