Files
income_calculator/backend/api/import_api.py
2026-02-23 16:49:24 +03:00

34 lines
1.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import os
import tempfile
from pathlib import Path
from fastapi import APIRouter, File, HTTPException, UploadFile
from backend.services.import_service import import_file, import_from_statements_dir
router = APIRouter(prefix="/api/import", tags=["import"])
@router.post("/upload")
async def upload_statement(file: UploadFile = File(...)):
if not file.filename or not file.filename.lower().endswith(".pdf"):
raise HTTPException(status_code=400, detail="Only PDF files are allowed")
if not (file.filename.startswith("Т-") or file.filename.startswith("С-") or file.filename.startswith("Я-")):
raise HTTPException(status_code=400, detail="Поддерживаются выписки Т-, С- и Я-банка (Т/С/Я-MM-YY.pdf)")
suffix = Path(file.filename).suffix
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
content = await file.read()
tmp.write(content)
tmp_path = tmp.name
try:
added, skipped, parsed = import_file(tmp_path, file.filename)
return {"added": added, "skipped_duplicates": skipped, "parsed": parsed, "filename": file.filename}
finally:
os.unlink(tmp_path)
@router.post("/from-folder")
def import_from_folder():
added, skipped, parsed = import_from_statements_dir()
return {"added": added, "skipped_duplicates": skipped, "parsed": parsed}