Files
leocrm/app/routes/import_export.py
T
Agent Zero a3a5a10514 Phase 1: Workflows UI, Dedup/Merge UI, Import/Export UI, Print/PDF
- Workflows UI: full page with definitions/instances tabs, step editor, instance detail with approve/reject
- Dedup/Merge UI: duplicate detection, side-by-side comparison, field-level merge dialog, merge history
- Import/Export UI: import wizard (dry-run preview), export panel (CSV/XLSX), backend export route added
- Print/PDF: PrintButton component, print.css, integrated in Contacts/Calendar/Reports/ContactDetail
- Backend: GET /api/v1/export endpoint, export_companies_csv() service function
- Routes: /workflows, /contacts/dedup, /import-export registered
- Menu items: Workflows, Import/Export, Duplikate added to automation plugin manifest
- IMPLEMENTATION_PLAN.md: audit-corrected plan for all 14 remaining features
2026-07-26 02:35:44 +02:00

152 lines
4.5 KiB
Python

"""Import/export routes — CSV import, dry-run preview, CSV/XLSX export."""
from __future__ import annotations
import io
import uuid
from fastapi import (
APIRouter,
Depends,
File,
Form,
HTTPException,
Query,
UploadFile,
)
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.responses import StreamingResponse
from app.core.db import get_db
from app.deps import require_permission
from app.services import import_export_service
router = APIRouter(prefix="/api/v1", tags=["import_export"])
@router.post("/import")
async def import_csv(
file: UploadFile = File(...),
entity_type: str = Form("companies"),
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("import_export:write")),
):
"""Import companies or contacts from CSV file.
entity_type: 'companies' or 'contacts'.
"""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
content = await file.read()
csv_content = content.decode("utf-8")
result = await import_export_service.import_csv(
db,
tenant_id,
user_id,
csv_content,
entity_type=entity_type,
dry_run=False,
)
return result
@router.post("/import/preview")
async def import_csv_preview(
file: UploadFile = File(...),
entity_type: str = Form("companies"),
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("import_export:read")),
):
"""Preview CSV import (dry-run — no DB changes)."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
content = await file.read()
csv_content = content.decode("utf-8")
result = await import_export_service.import_csv(
db,
tenant_id,
user_id,
csv_content,
entity_type=entity_type,
dry_run=True,
)
return result
@router.get("/export")
async def export_data(
entity_type: str = Query("contacts", pattern="^(contacts|companies)$"),
format: str = Query("csv", pattern="^(csv|xlsx)$"),
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("import_export:read")),
):
"""Export contacts or companies as CSV or XLSX file download.
Query params:
- entity_type: 'contacts' or 'companies' (default: contacts)
- format: 'csv' or 'xlsx' (default: csv)
"""
tenant_id = uuid.UUID(current_user["tenant_id"])
# Determine filename based on entity_type
filename = f"{entity_type}_export.csv"
# Fetch CSV data from the appropriate service function
if entity_type == "contacts":
csv_data = await import_export_service.export_contacts_csv(db, tenant_id)
elif entity_type == "companies":
csv_data = await import_export_service.export_companies_csv(db, tenant_id)
else:
raise HTTPException(status_code=400, detail=f"Unsupported entity_type: {entity_type}")
# XLSX format handling
if format == "xlsx":
try:
import openpyxl
wb = openpyxl.Workbook()
ws = wb.active
ws.title = entity_type.capitalize()
# Parse the CSV string and populate the worksheet
import csv as _csv
reader = _csv.reader(io.StringIO(csv_data))
for row in reader:
ws.append(row)
xlsx_buffer = io.BytesIO()
wb.save(xlsx_buffer)
xlsx_buffer.seek(0)
xlsx_filename = f"{entity_type}_export.xlsx"
return StreamingResponse(
xlsx_buffer,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={"Content-Disposition": f'attachment; filename="{xlsx_filename}"'},
)
except ImportError:
# openpyxl not available — fall back to CSV with a warning header
media_type = "text/csv"
headers = {
"Content-Disposition": f'attachment; filename="{filename}"',
"X-Export-Warning": "openpyxl not installed, falling back to CSV format",
}
return StreamingResponse(
iter([csv_data.encode("utf-8")]),
media_type=media_type,
headers=headers,
)
# Default: CSV format
return StreamingResponse(
iter([csv_data.encode("utf-8")]),
media_type="text/csv",
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
)