2026-06-29 00:44:34 +02:00
|
|
|
"""Import/export routes — CSV import, dry-run preview, CSV/XLSX export."""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
2026-07-26 02:35:44 +02:00
|
|
|
import io
|
2026-06-29 00:44:34 +02:00
|
|
|
import uuid
|
|
|
|
|
|
2026-06-29 17:43:56 +02:00
|
|
|
from fastapi import (
|
|
|
|
|
APIRouter,
|
|
|
|
|
Depends,
|
|
|
|
|
File,
|
|
|
|
|
Form,
|
|
|
|
|
HTTPException,
|
2026-07-26 02:35:44 +02:00
|
|
|
Query,
|
2026-06-29 17:43:56 +02:00
|
|
|
UploadFile,
|
|
|
|
|
)
|
2026-06-29 00:44:34 +02:00
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
2026-07-26 02:35:44 +02:00
|
|
|
from starlette.responses import StreamingResponse
|
2026-06-29 00:44:34 +02:00
|
|
|
|
|
|
|
|
from app.core.db import get_db
|
2026-07-15 22:35:50 +02:00
|
|
|
from app.deps import require_permission
|
2026-06-29 00:44:34 +02:00
|
|
|
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),
|
2026-07-15 22:35:50 +02:00
|
|
|
current_user: dict = Depends(require_permission("import_export:write")),
|
2026-06-29 00:44:34 +02:00
|
|
|
):
|
|
|
|
|
"""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(
|
2026-06-29 17:43:56 +02:00
|
|
|
db,
|
|
|
|
|
tenant_id,
|
|
|
|
|
user_id,
|
|
|
|
|
csv_content,
|
|
|
|
|
entity_type=entity_type,
|
|
|
|
|
dry_run=False,
|
2026-06-29 00:44:34 +02:00
|
|
|
)
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.post("/import/preview")
|
|
|
|
|
async def import_csv_preview(
|
|
|
|
|
file: UploadFile = File(...),
|
|
|
|
|
entity_type: str = Form("companies"),
|
|
|
|
|
db: AsyncSession = Depends(get_db),
|
2026-07-15 22:35:50 +02:00
|
|
|
current_user: dict = Depends(require_permission("import_export:read")),
|
2026-06-29 00:44:34 +02:00
|
|
|
):
|
|
|
|
|
"""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(
|
2026-06-29 17:43:56 +02:00
|
|
|
db,
|
|
|
|
|
tenant_id,
|
|
|
|
|
user_id,
|
|
|
|
|
csv_content,
|
|
|
|
|
entity_type=entity_type,
|
|
|
|
|
dry_run=True,
|
2026-06-29 00:44:34 +02:00
|
|
|
)
|
|
|
|
|
return result
|
2026-07-26 02:35:44 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@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"])
|
2026-07-29 02:11:29 +02:00
|
|
|
user_id = uuid.UUID(current_user["user_id"])
|
|
|
|
|
is_system_admin = current_user.get("is_system_admin", False)
|
2026-07-26 02:35:44 +02:00
|
|
|
|
|
|
|
|
# Determine filename based on entity_type
|
|
|
|
|
filename = f"{entity_type}_export.csv"
|
|
|
|
|
|
|
|
|
|
# Fetch CSV data from the appropriate service function
|
|
|
|
|
if entity_type == "contacts":
|
2026-07-29 02:11:29 +02:00
|
|
|
csv_data = await import_export_service.export_contacts_csv(
|
|
|
|
|
db, tenant_id, user_id=user_id, is_system_admin=is_system_admin
|
|
|
|
|
)
|
2026-07-26 02:35:44 +02:00
|
|
|
elif entity_type == "companies":
|
2026-07-29 02:11:29 +02:00
|
|
|
csv_data = await import_export_service.export_companies_csv(
|
|
|
|
|
db, tenant_id, user_id=user_id, is_system_admin=is_system_admin
|
|
|
|
|
)
|
2026-07-26 02:35:44 +02:00
|
|
|
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}"'},
|
|
|
|
|
)
|