c-stone-invoice-check/backend/tests/test_outbound.py
Markus Kruse c6b84db0d2 feat(picker): Whop-Roboter (Login per Mail-Code, PDF via receipt_pdf)
Belegnummern aus Order-Confirmation-Mails, Login-Cookies im Volume,
Whop-Mails nicht mehr als manual. Chromium im Backend-Image.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Wd9aeH8MKgesfbsaS3kpnx
2026-11-15 09:57:35 +01:00

99 lines
5.5 KiB
Python

import email
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from backend import grabber
from backend.models import Base, Outbound
LINK = ("Message-ID: <{mid}>\nSubject: Ihre Rechnung\nFrom: Shop <billing@shop.example>\n"
"Date: {date}\nContent-Type: text/plain\n\nDownload: https://pay.stripe.com/invoice/x/pdf")
PORTAL = ("Message-ID: <p1>\nSubject: Rechnung verfügbar\nFrom: AWS <no@aws.example>\n"
"Date: Mon, 3 Nov 2025 10:00:00 +0000\nContent-Type: text/plain\n\nSee https://console.aws.amazon.com/billing")
def test_process_message(tmp_path, monkeypatch):
db = sessionmaker(bind=create_engine("sqlite://"))()
Base.metadata.create_all(db.get_bind())
monkeypatch.setattr(grabber, "fetch_pdf", lambda url: b"%PDF-1.4 same")
monkeypatch.setenv("GRAB_CUTOFF", "2026-11-13")
run = lambda raw: grabber.process_message(db, email.message_from_string(raw), "INBOX", str(tmp_path))
assert run(LINK.format(mid="a", date="Mon, 3 Nov 2025 10:00:00 +0000")) == "pending_review" # Rückblick
assert run(LINK.format(mid="a", date="Mon, 3 Nov 2025 10:00:00 +0000")) is None # gleiche Message-ID
assert run(LINK.format(mid="b", date="Mon, 3 Nov 2025 10:00:00 +0000")) == "duplicate" # gleiche PDF
monkeypatch.setattr(grabber, "fetch_pdf", lambda url: b"%PDF-1.4 neu")
assert run(LINK.format(mid="c", date="Mon, 16 Nov 2026 10:00:00 +0000")) == "queued" # nach Stichtag
assert run(PORTAL) == "manual"
assert run("Subject: Newsletter\n\nhallo") is None
assert db.query(Outbound).count() == 4
assert (tmp_path / "picker" / "2025" / "11").is_dir()
monkeypatch.delenv("GRAB_CUTOFF") # ohne Stichtag nie automatisch senden
monkeypatch.setattr(grabber, "fetch_pdf", lambda url: b"%PDF-1.4 dritte")
assert run(LINK.format(mid="d", date="Mon, 16 Nov 2026 10:00:00 +0000")) == "pending_review"
def test_aws(tmp_path, monkeypatch):
from datetime import date, datetime, timezone
db = sessionmaker(bind=create_engine("sqlite://"))()
Base.metadata.create_all(db.get_bind())
monkeypatch.setattr(grabber.aws, "ENABLED", True)
calls = []
def fake(since, known):
calls.append(set(known))
for iid in ("EUINDE1", "EUINDE2"):
if iid not in known:
yield {"invoice_id": iid, "issued": datetime(2025, 12, 2, tzinfo=timezone.utc), "period": "2025-11",
"entity": "AWS", "pdf": f"%PDF-1.4 {iid}".encode()}
monkeypatch.setattr(grabber.aws, "fetch_invoices", fake)
counts = {}
grabber.sync_aws(db, date(2025, 1, 1), str(tmp_path), counts)
grabber.sync_aws(db, date(2025, 1, 1), str(tmp_path), counts) # zweiter Lauf: nichts Neues
assert counts == {"pending_review": 2} and calls[1] == {"EUINDE1", "EUINDE2"}
# AWS-Hinweismail wird nicht mehr als "manual" geführt
mail = ("Message-ID: <aws1>\nSubject: Amazon Web Services Tax Invoice Available\nFrom: AWS <no-reply@aws.com>\n"
"Content-Type: text/plain\n\nSee https://console.aws.amazon.com/billing")
assert grabber.process_message(db, email.message_from_string(mail), "INBOX", str(tmp_path)) is None
fake_aws = mail.replace("aws.com", "notaws.com").replace("<aws1>", "<aws2>")
assert grabber.process_message(db, email.message_from_string(fake_aws), "INBOX", str(tmp_path)) == "manual"
def test_gmail_nur_rueckblick_und_bericht(monkeypatch):
from datetime import date, datetime
from backend import mailer
db = sessionmaker(bind=create_engine("sqlite://"))()
Base.metadata.create_all(db.get_bind())
monkeypatch.setattr(grabber, "get_imap_config", lambda db: {"host": "imap.strato.de", "storage_path": "/x"})
monkeypatch.setenv("GMAIL_IMAP_PASSWORD", "x")
hosts = lambda since: [c["host"] for c, _ in grabber._mailboxes(db, since)]
assert hosts(date(2025, 1, 1)) == ["imap.strato.de", "imap.gmail.com"]
assert hosts(date(2026, 11, 5)) == ["imap.strato.de"]
db.add(Outbound(message_id="m1", status="manual", email_date=datetime(2026, 11, 10),
email_from="Shop", email_subject="Rechnung verfügbar"))
db.commit()
txt = mailer.report_text(db, {"counts": {"manual": 1}, "errors": []}, date(2026, 11, 5))
assert "Manuell abholen" in txt and "Rechnung verfügbar" in txt
def test_whop(tmp_path, monkeypatch):
from datetime import date
from backend.fetchers import whop
mail = ("Message-ID: <w1>\nSubject: Whop Ads Order Confirmation\nFrom: Whop Ads via Whop <no-reply@businesses.whop.com>\n"
"Date: Thu, 12 Nov 2026 10:00:00 +0000\nContent-Type: text/html\n\n"
"<p>Amount paid $15.01</p><p>Receipt NJlZDb5nDSnaFK</p>")
rec = whop.parse_receipt(email.message_from_string(mail))
assert rec["pay_id"] == "pay_NJlZDb5nDSnaFK" and rec["amount"] == "15.01" and rec["date"].tzinfo is None
db = sessionmaker(bind=create_engine("sqlite://"))()
Base.metadata.create_all(db.get_bind())
monkeypatch.setattr(whop, "receipts", lambda cfg, since: [rec])
calls = []
monkeypatch.setattr(whop, "fetch_pdfs", lambda cfg, ids, st: calls.append(ids) or {i: b"%PDF-1.4 w" for i in ids})
cfg, counts = {"storage_path": str(tmp_path)}, {}
grabber.sync_whop(db, cfg, date(2026, 11, 1), counts)
grabber.sync_whop(db, cfg, date(2026, 11, 1), counts) # zweiter Lauf: nichts Neues, kein Browser
assert counts == {"pending_review": 1} and len(calls) == 1
monkeypatch.setattr(whop, "ENABLED", True)
assert grabber.process_message(db, email.message_from_string(mail), "INBOX", str(tmp_path)) is None