- Klassifikator: Direktlink nur Allowlist/https-PDF, Login-/Konsolen-Links -> portal - grabber.py: INBOX/Archive/Trash readonly, Dedupe Message-ID + SHA-256 - Stichtag GRAB_CUTOFF: Rückblick = pending_review, neu = queued - mailer.py: SMTP an ACCOUNTABLE_INBOX (ohne Adresse kein Versand) - /outbound: Liste/xlsx, PDF-Vorschau, approve, run Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
97 lines
3.5 KiB
Python
97 lines
3.5 KiB
Python
"""Invoice Picker: gezogene Rechnungen ansehen, Rückblick freigeben, an Accountable senden."""
|
|
|
|
import io
|
|
import os
|
|
import uuid
|
|
from datetime import datetime
|
|
from typing import List, Optional
|
|
|
|
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
|
from fastapi.responses import FileResponse, StreamingResponse
|
|
from pydantic import BaseModel
|
|
from sqlalchemy.orm import Session
|
|
|
|
from backend import grabber, mailer
|
|
from backend.database import SessionLocal, get_db
|
|
from backend.models import Outbound
|
|
|
|
router = APIRouter()
|
|
_runs: dict = {} # ponytail: in-memory Laufstatus, ein Prozess
|
|
|
|
|
|
def _bg_run(run_id: str, since):
|
|
db = SessionLocal()
|
|
try:
|
|
grabber.run(db, since, _runs[run_id])
|
|
_runs[run_id]["send"] = mailer.send_queued(db)
|
|
except Exception as e:
|
|
_runs[run_id]["errors"].append(str(e))
|
|
finally:
|
|
_runs[run_id]["status"] = "done"
|
|
db.close()
|
|
|
|
|
|
@router.post("/run")
|
|
async def start_run(background_tasks: BackgroundTasks, since: str):
|
|
"""Postfach ab since (YYYY-MM-DD) prüfen, Rechnungen ziehen, freigegebene/neue senden."""
|
|
if any(r["status"] == "running" for r in _runs.values()):
|
|
raise HTTPException(409, "Lauf aktiv")
|
|
run_id = str(uuid.uuid4())
|
|
_runs[run_id] = {"status": "running", "errors": [], "counts": {}, "start": datetime.utcnow().isoformat()}
|
|
background_tasks.add_task(_bg_run, run_id, datetime.strptime(since, "%Y-%m-%d").date())
|
|
return {"run_id": run_id}
|
|
|
|
|
|
@router.get("/run/{run_id}")
|
|
async def run_status(run_id: str):
|
|
if run_id not in _runs:
|
|
raise HTTPException(404, "Lauf nicht gefunden")
|
|
return _runs[run_id]
|
|
|
|
|
|
@router.get("")
|
|
async def list_outbound(status: Optional[str] = None, format: str = "json", db: Session = Depends(get_db)):
|
|
q = db.query(Outbound)
|
|
if status:
|
|
q = q.filter(Outbound.status == status)
|
|
rows = q.order_by(Outbound.email_date.desc()).all()
|
|
data = [{"id": r.id, "status": r.status, "datum": f"{r.email_date:%Y-%m-%d}" if r.email_date else "",
|
|
"absender": r.email_from, "betreff": r.email_subject, "klasse": r.mail_class,
|
|
"link": r.link_url or "", "datei": os.path.basename(r.file_path or ""), "fehler": r.error or ""}
|
|
for r in rows]
|
|
if format != "xlsx":
|
|
return data
|
|
from openpyxl import Workbook
|
|
wb = Workbook()
|
|
ws = wb.active
|
|
ws.append(list(data[0].keys()) if data else ["leer"])
|
|
for d in data:
|
|
ws.append(list(d.values()))
|
|
buf = io.BytesIO()
|
|
wb.save(buf)
|
|
buf.seek(0)
|
|
return StreamingResponse(buf, media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
headers={"Content-Disposition": "attachment; filename=invoice-picker.xlsx"})
|
|
|
|
|
|
@router.get("/{oid}/pdf")
|
|
async def get_pdf(oid: int, db: Session = Depends(get_db)):
|
|
r = db.get(Outbound, oid)
|
|
if not r or not r.file_path or not os.path.exists(r.file_path):
|
|
raise HTTPException(404, "kein PDF")
|
|
return FileResponse(r.file_path, media_type="application/pdf")
|
|
|
|
|
|
class Approve(BaseModel):
|
|
ids: Optional[List[int]] = None # None = alle wartenden
|
|
|
|
|
|
@router.post("/approve")
|
|
async def approve(body: Approve, db: Session = Depends(get_db)):
|
|
"""Rückblick freigeben (pending_review -> queued) und sofort senden."""
|
|
q = db.query(Outbound).filter(Outbound.status == "pending_review")
|
|
if body.ids is not None:
|
|
q = q.filter(Outbound.id.in_(body.ids))
|
|
n = q.update({Outbound.status: "queued"}, synchronize_session=False)
|
|
db.commit()
|
|
return {"approved": n, **mailer.send_queued(db)}
|