|
|
"""Bulk export endpoint.""" |
|
|
|
|
|
import os |
|
|
import logging |
|
|
from fastapi import APIRouter, HTTPException, Depends, BackgroundTasks |
|
|
from fastapi.responses import FileResponse |
|
|
|
|
|
from api.schemas import BulkExportRequest |
|
|
from services.database import db_service |
|
|
from services.export_service import export_service |
|
|
from services.auth_dependency import get_current_user |
|
|
|
|
|
router = APIRouter(tags=["export"]) |
|
|
api_logger = logging.getLogger("api") |
|
|
|
|
|
|
|
|
@router.post("/api/export/bulk") |
|
|
async def export_bulk_ads( |
|
|
request: BulkExportRequest, |
|
|
background_tasks: BackgroundTasks, |
|
|
username: str = Depends(get_current_user), |
|
|
): |
|
|
""" |
|
|
Export multiple ad creatives as a ZIP package. |
|
|
Creates /creatives/ folder and ad_copy_data.xlsx. Max 50 ads. |
|
|
""" |
|
|
if len(request.ad_ids) > 50: |
|
|
raise HTTPException(status_code=400, detail="Maximum 50 ads can be exported at once") |
|
|
ads = [] |
|
|
for ad_id in request.ad_ids: |
|
|
ad = await db_service.get_ad_creative(ad_id, username=username) |
|
|
if not ad: |
|
|
raise HTTPException(status_code=404, detail=f"Ad '{ad_id}' not found or access denied") |
|
|
ads.append(ad) |
|
|
try: |
|
|
api_logger.info("Creating export package for %d ads (user: %s)", len(ads), username) |
|
|
zip_path = await export_service.create_export_package(ads) |
|
|
background_tasks.add_task(export_service.cleanup_zip, zip_path) |
|
|
return FileResponse( |
|
|
zip_path, |
|
|
media_type="application/zip", |
|
|
filename=os.path.basename(zip_path), |
|
|
) |
|
|
except HTTPException: |
|
|
raise |
|
|
except Exception as e: |
|
|
api_logger.error("Bulk export failed: %s", e) |
|
|
raise HTTPException(status_code=500, detail=f"Export failed: {str(e)}") |
|
|
|