feat: Vorschlaege buchen und Telefon-Dateien nur ablegen
Zwei Luecken geschlossen: Mail-Vorschlaege standen als "pending" im Eingang, aber es gab keinen Knopf zum Buchen – der Weg war hinten offen. Jetzt je Eintrag "Buchen" und ein "Alle buchen". Unklare bleiben liegen: Bei ihnen fehlt etwas oder die Erkennung war unsicher, die soll man ansehen statt im Stapel durchzuwinken. Der Auszug vom Telefon bucht nicht mehr sofort, sondern wird nur abgelegt. Am Telefon prueft man keine 500 Zeilen; die Datei wartet in der Import-Ansicht und laeuft dort durch die normale Vorschau mit Saldo-Abgleich, Zeilenfilter und Duplikatpruefung. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -23,6 +23,7 @@ from sqlalchemy import (
|
||||
Enum as SAEnum,
|
||||
ForeignKey,
|
||||
Integer,
|
||||
LargeBinary,
|
||||
Numeric,
|
||||
String,
|
||||
Text,
|
||||
@@ -744,3 +745,27 @@ class MailSender(Base):
|
||||
ForeignKey("accounts.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
|
||||
|
||||
|
||||
class PendingUpload(Base):
|
||||
"""Eine vom Telefon abgelieferte Datei, die noch niemand geprüft hat.
|
||||
|
||||
Am Telefon lässt sich ein Auszug nicht sinnvoll durchsehen – hunderte
|
||||
Zeilen mit Kategorie-Auswahl sind auf dem Bildschirm keine Erleichterung.
|
||||
Die Datei wird deshalb nur entgegengenommen; geprüft und gebucht wird
|
||||
später in der normalen Import-Ansicht, mit Saldo-Abgleich und allem.
|
||||
"""
|
||||
|
||||
__tablename__ = "pending_uploads"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
owner_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
|
||||
)
|
||||
account_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
filename: Mapped[str] = mapped_column(String(255), nullable=False, default="")
|
||||
content: Mapped[bytes] = mapped_column(LargeBinary, nullable=False)
|
||||
size_bytes: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
|
||||
|
||||
@@ -7,7 +7,9 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..deps import get_current_user, get_owned
|
||||
from ..models import Account, AmountMode, ImportBatch, ImportStatus, ImportTemplate, User
|
||||
from fastapi.responses import Response
|
||||
|
||||
from ..models import PendingUpload, Account, AmountMode, ImportBatch, ImportStatus, ImportTemplate, User
|
||||
from ..schemas import (
|
||||
ImportBatchOut,
|
||||
ImportCommitIn,
|
||||
@@ -179,3 +181,39 @@ def remove_batch_record(
|
||||
)
|
||||
db.delete(batch)
|
||||
db.commit()
|
||||
|
||||
|
||||
# --- Vom Telefon abgelieferte Dateien ---------------------------------------
|
||||
|
||||
|
||||
@router.get("/uploads")
|
||||
def list_uploads(db: Session = Depends(get_db), user: User = Depends(get_current_user)) -> list[dict]:
|
||||
"""Wartende Dateien. Der Inhalt bleibt hier draussen – nur die Eckdaten."""
|
||||
zeilen = (
|
||||
db.query(PendingUpload)
|
||||
.filter(PendingUpload.owner_id == user.id)
|
||||
.order_by(PendingUpload.created_at.desc(), PendingUpload.id.desc())
|
||||
.all()
|
||||
)
|
||||
return [
|
||||
{"id": u.id, "filename": u.filename, "account_id": u.account_id,
|
||||
"size_bytes": u.size_bytes, "created_at": u.created_at.isoformat() if u.created_at else None}
|
||||
for u in zeilen
|
||||
]
|
||||
|
||||
|
||||
@router.get("/uploads/{upload_id}/content")
|
||||
def upload_content(upload_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
"""Die Datei selbst – damit die Import-Ansicht sie wie eine lokale behandelt."""
|
||||
upload = get_owned(db, PendingUpload, upload_id, user)
|
||||
return Response(
|
||||
content=upload.content,
|
||||
media_type="text/csv",
|
||||
headers={"Content-Disposition": f'attachment; filename="{upload.filename}"'},
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/uploads/{upload_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_upload(upload_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
db.delete(get_owned(db, PendingUpload, upload_id, user))
|
||||
db.commit()
|
||||
|
||||
@@ -10,9 +10,18 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..deps import get_current_user, get_owned
|
||||
from ..models import Account, ApiToken, InboxItem, InboxStatus, Transaction, User
|
||||
from ..models import (
|
||||
Account,
|
||||
ApiToken,
|
||||
InboxItem,
|
||||
InboxStatus,
|
||||
Transaction,
|
||||
TxnType,
|
||||
User,
|
||||
)
|
||||
from ..schemas import ApiTokenCreate, ApiTokenCreated, ApiTokenOut, InboxItemOut
|
||||
from ..security import generate_session_token, hash_session_token
|
||||
from ..services import currency
|
||||
|
||||
router = APIRouter(prefix="/inbox", tags=["inbox"])
|
||||
|
||||
@@ -77,6 +86,68 @@ def list_inbox(
|
||||
)
|
||||
|
||||
|
||||
def _buche(db: Session, user: User, eintrag: InboxItem) -> Transaction | None:
|
||||
"""Aus einem Vorschlag eine Buchung machen. Ohne Konto geht es nicht."""
|
||||
if eintrag.status == InboxStatus.booked or eintrag.transaction_id is not None:
|
||||
return None
|
||||
if eintrag.account_id is None:
|
||||
return None
|
||||
konto = db.get(Account, eintrag.account_id)
|
||||
if konto is None or konto.owner_id != user.id:
|
||||
return None
|
||||
betrag = abs(eintrag.amount_cents)
|
||||
txn = Transaction(
|
||||
owner_id=user.id,
|
||||
type=TxnType.expense if eintrag.amount_cents < 0 else TxnType.income,
|
||||
date=eintrag.date,
|
||||
account_id=konto.id,
|
||||
amount_cents=betrag,
|
||||
amount_eur_cents=currency.compute_amount_eur_cents(
|
||||
db, betrag, konto.currency, eintrag.date),
|
||||
category_id=eintrag.category_id,
|
||||
payee=eintrag.payee,
|
||||
description=eintrag.note,
|
||||
)
|
||||
db.add(txn)
|
||||
db.flush()
|
||||
eintrag.transaction_id = txn.id
|
||||
eintrag.status = InboxStatus.booked
|
||||
return txn
|
||||
|
||||
|
||||
@router.post("/{item_id}/book", response_model=InboxItemOut)
|
||||
def book_item(item_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
eintrag = get_owned(db, InboxItem, item_id, user)
|
||||
if eintrag.account_id is None:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Kein Konto zugeordnet")
|
||||
if _buche(db, user, eintrag) is None:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Lässt sich nicht buchen")
|
||||
db.commit()
|
||||
db.refresh(eintrag)
|
||||
return eintrag
|
||||
|
||||
|
||||
@router.post("/book-all")
|
||||
def book_all(db: Session = Depends(get_db), user: User = Depends(get_current_user)) -> dict:
|
||||
"""Alle offenen Vorschläge buchen, die ein Konto haben.
|
||||
|
||||
Unklare bleiben liegen: Bei ihnen fehlt etwas oder die Erkennung war
|
||||
unsicher – die soll man ansehen, nicht im Stapel durchwinken.
|
||||
"""
|
||||
offen = (
|
||||
db.query(InboxItem)
|
||||
.filter(InboxItem.owner_id == user.id,
|
||||
InboxItem.status == InboxStatus.pending,
|
||||
InboxItem.account_id.isnot(None))
|
||||
.all()
|
||||
)
|
||||
gebucht = sum(1 for e in offen if _buche(db, user, e) is not None)
|
||||
db.commit()
|
||||
return {"gebucht": gebucht}
|
||||
|
||||
|
||||
@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def discard_item(item_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
"""Eintrag verwerfen – samt der Buchung, die daraus entstanden ist.
|
||||
|
||||
@@ -13,8 +13,6 @@ Auswahl braucht – sie liefert nur Name, Symbol und Farbe, keine Salden.
|
||||
from datetime import date as date_t
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
|
||||
import json
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -23,13 +21,11 @@ from ..deps import require_quick_token
|
||||
from ..models import (
|
||||
Account,
|
||||
ApiToken,
|
||||
ImportBatch,
|
||||
ImportStatus,
|
||||
ImportTemplate,
|
||||
InboxItem,
|
||||
InboxSource,
|
||||
InboxStatus,
|
||||
Transaction,
|
||||
PendingUpload,
|
||||
TxnType,
|
||||
User,
|
||||
)
|
||||
@@ -151,34 +147,8 @@ def quick_booking(
|
||||
)
|
||||
|
||||
|
||||
def _letzte_vorlage(db: Session, konto: Account) -> ImportTemplate | None:
|
||||
"""Die Einstellung, mit der dieses Konto zuletzt erfolgreich eingelesen wurde.
|
||||
|
||||
Am Telefon lässt sich keine Spaltenzuordnung vornehmen. Der Kurzbefehl
|
||||
setzt deshalb voraus, dass die Datei am Rechner schon einmal für dieses
|
||||
Konto eingelesen wurde – dann steht im Import-Verlauf, wie es ging.
|
||||
"""
|
||||
stapel = (
|
||||
db.query(ImportBatch)
|
||||
.filter(ImportBatch.owner_id == konto.owner_id,
|
||||
ImportBatch.account_id == konto.id,
|
||||
ImportBatch.status == ImportStatus.committed)
|
||||
.order_by(ImportBatch.created_at.desc(), ImportBatch.id.desc())
|
||||
.first()
|
||||
)
|
||||
if stapel is None:
|
||||
return None
|
||||
if stapel.template_id:
|
||||
vorlage = db.get(ImportTemplate, stapel.template_id)
|
||||
if vorlage is not None and vorlage.owner_id == konto.owner_id:
|
||||
return vorlage
|
||||
if stapel.preset:
|
||||
for p in csv_import.PRESETS:
|
||||
if p["name"] == stapel.preset:
|
||||
felder = {k: v for k, v in p.items() if k not in ("name", "column_map")}
|
||||
return ImportTemplate(owner_id=konto.owner_id, name="_kurzbefehl",
|
||||
column_map=json.dumps(p["column_map"]), **felder)
|
||||
return None
|
||||
# Grosszuegig, aber nicht unbegrenzt: Ein Jahresauszug liegt weit darunter.
|
||||
MAX_UPLOAD = 5 * 1024 * 1024
|
||||
|
||||
|
||||
@router.post("/statement", status_code=status.HTTP_201_CREATED)
|
||||
@@ -188,43 +158,37 @@ async def quick_statement(
|
||||
marke: ApiToken = Depends(require_quick_token),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
"""Kontoauszug vom Telefon aus einlesen (Teilen-Menü).
|
||||
"""Kontoauszug vom Telefon entgegennehmen (Teilen-Menü).
|
||||
|
||||
Gebucht wird sofort – ein Auszug hat schnell hunderte Zeilen, die einzeln
|
||||
abzunicken wäre keine Erleichterung. Sicher ist das, weil die
|
||||
Duplikaterkennung greift und der ganze Stapel im Import-Verlauf mit einem
|
||||
Klick rückgängig zu machen ist.
|
||||
Hier wird NICHT gebucht. Ein Auszug hat schnell hunderte Zeilen; die am
|
||||
Telefon durchzusehen wäre keine Erleichterung. Die Datei wird abgelegt und
|
||||
wartet in der Import-Ansicht – dort gibt es Vorschau, Saldo-Abgleich und
|
||||
die Möglichkeit, einzelne Zeilen abzuwählen.
|
||||
"""
|
||||
konto = _konto(db, marke, account_id)
|
||||
user = db.get(User, marke.owner_id)
|
||||
vorlage = _letzte_vorlage(db, konto)
|
||||
if vorlage is None:
|
||||
daten = await file.read()
|
||||
if not daten:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Datei ist leer")
|
||||
if len(daten) > MAX_UPLOAD:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=(f"Für „{konto.name}“ gibt es noch keine Einstellung. Bitte einen Auszug "
|
||||
"dieses Kontos einmal am Rechner einlesen – danach geht es vom Telefon."),
|
||||
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
|
||||
detail=f"Datei zu gross ({len(daten) // 1024} KB, erlaubt sind "
|
||||
f"{MAX_UPLOAD // 1024 // 1024} MB)",
|
||||
)
|
||||
|
||||
daten = await file.read()
|
||||
try:
|
||||
kandidaten = csv_import.parse_file_to_candidates(daten, vorlage)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Datei nicht lesbar: {e}") from e
|
||||
|
||||
zeilen = csv_import.detect_rows(db, user, konto, kandidaten)
|
||||
zu_buchen = [z for z in zeilen if z.get("include")]
|
||||
stapel = csv_import.commit_import(
|
||||
db, user, konto, vorlage.id if vorlage.id else None,
|
||||
(file.filename or "Vom Telefon")[:255], zu_buchen,
|
||||
preset=None if vorlage.id else vorlage.name,
|
||||
upload = PendingUpload(
|
||||
owner_id=marke.owner_id,
|
||||
account_id=konto.id,
|
||||
filename=(file.filename or "Vom Telefon")[:255],
|
||||
content=daten,
|
||||
size_bytes=len(daten),
|
||||
)
|
||||
dubletten = sum(1 for z in zeilen if z.get("is_duplicate"))
|
||||
db.add(upload)
|
||||
db.commit()
|
||||
db.refresh(upload)
|
||||
return {
|
||||
"gelesen": len(zeilen),
|
||||
"gebucht": stapel.imported_count,
|
||||
"duplikate": dubletten,
|
||||
"id": upload.id,
|
||||
"konto": konto.name,
|
||||
"message": f"{stapel.imported_count} gebucht auf {konto.name}"
|
||||
f" · {dubletten} schon vorhanden",
|
||||
"size_bytes": upload.size_bytes,
|
||||
"message": f"Empfangen für {konto.name} – zum Prüfen in Certain öffnen",
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Vom Telefon abgelieferte Dateien, die noch niemand geprueft hat.
|
||||
|
||||
Am Telefon laesst sich ein Auszug mit hunderten Zeilen nicht sinnvoll
|
||||
durchsehen. Die Datei wird deshalb nur entgegengenommen und spaeter in der
|
||||
normalen Import-Ansicht geprueft – mit Vorschau, Saldo-Abgleich und der
|
||||
Moeglichkeit, einzelne Zeilen abzuwaehlen.
|
||||
|
||||
Revision ID: 0019
|
||||
Revises: 0018
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0019"
|
||||
down_revision = "0018"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"pending_uploads",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("owner_id", sa.Integer(), nullable=False),
|
||||
sa.Column("account_id", sa.Integer(), nullable=False),
|
||||
sa.Column("filename", sa.String(length=255), nullable=False, server_default=""),
|
||||
sa.Column("content", sa.LargeBinary(), nullable=False),
|
||||
sa.Column("size_bytes", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.ForeignKeyConstraint(["owner_id"], ["users.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(["account_id"], ["accounts.id"], ondelete="CASCADE"),
|
||||
)
|
||||
op.create_index("ix_pending_uploads_owner_id", "pending_uploads", ["owner_id"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("pending_uploads")
|
||||
@@ -399,3 +399,48 @@ def test_zuordnung_mit_waehrung_schlaegt_die_allgemeine(admin, monkeypatch):
|
||||
|
||||
treffer = [e for e in admin.get("/api/inbox").json() if e["amount_cents"] == -1200]
|
||||
assert treffer and treffer[0]["account_id"] == eur["id"]
|
||||
|
||||
|
||||
def test_mailvorschlag_wird_erst_auf_knopfdruck_gebucht(admin, fake_imap):
|
||||
"""Eine Mail bucht nie von selbst – aber sie muss sich buchen lassen."""
|
||||
konto = _konto(admin, name="Buchbar", opening_balance_cents=0)
|
||||
quelle = _postfach(admin)
|
||||
admin.post(f"/api/mail/sources/{quelle['id']}/senders", json={
|
||||
"from_contains": "raiffeisen", "account_id": konto["id"]})
|
||||
|
||||
roh = (MUSTER / "raiffeisen_zahlungsstatus.eml").read_bytes().replace(
|
||||
b"<raiffeisen-muster-1@", b"<buchbar-1@")
|
||||
import unittest.mock as _m
|
||||
with _m.patch.object(mail_import, "_verbinden", lambda q: FakeImap([roh])):
|
||||
admin.post(f"/api/mail/sources/{quelle['id']}/fetch")
|
||||
|
||||
eintrag = [e for e in admin.get("/api/inbox").json()
|
||||
if e["account_id"] == konto["id"]][0]
|
||||
assert eintrag["status"] == "pending"
|
||||
assert admin.get(f"/api/accounts/{konto['id']}").json()["balance_cents"] == 0
|
||||
|
||||
r = admin.post(f"/api/inbox/{eintrag['id']}/book")
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["status"] == "booked"
|
||||
assert admin.get(f"/api/accounts/{konto['id']}").json()["balance_cents"] == -1490
|
||||
|
||||
# Zweimal buchen darf den Saldo nicht verdoppeln.
|
||||
admin.post(f"/api/inbox/{eintrag['id']}/book")
|
||||
assert admin.get(f"/api/accounts/{konto['id']}").json()["balance_cents"] == -1490
|
||||
|
||||
|
||||
def test_unklare_vorschlaege_werden_nicht_mitgebucht(admin, fake_imap):
|
||||
"""Ohne Zielkonto oder mit unsicherer Erkennung: liegen lassen, nicht durchwinken."""
|
||||
quelle = _postfach(admin)
|
||||
admin.post(f"/api/mail/sources/{quelle['id']}/senders", json={"from_contains": "revolut"})
|
||||
roh = (MUSTER / "revolut_ueberweisung.eml").read_bytes().replace(
|
||||
b"<revolut-muster-1@", b"<unklar-bleibt@")
|
||||
import unittest.mock as _m
|
||||
with _m.patch.object(mail_import, "_verbinden", lambda q: FakeImap([roh])):
|
||||
admin.post(f"/api/mail/sources/{quelle['id']}/fetch")
|
||||
|
||||
unklare = [e for e in admin.get("/api/inbox").json() if e["status"] == "unclear"]
|
||||
assert unklare
|
||||
admin.post("/api/inbox/book-all")
|
||||
danach = admin.get("/api/inbox").json()
|
||||
assert all(e["status"] == "unclear" for e in danach if e["id"] == unklare[0]["id"])
|
||||
|
||||
+51
-49
@@ -249,55 +249,6 @@ def test_zwei_gleiche_zahlungen_verbrauchen_je_einen_eintrag(admin):
|
||||
assert sum(1 for r in v["rows"] if r["include"]) == 1
|
||||
|
||||
|
||||
def test_auszug_vom_telefon_nutzt_die_zuletzt_benutzte_vorlage(admin):
|
||||
"""Am Telefon kann man keine Spalten zuordnen. Also wird die Einstellung
|
||||
wiederverwendet, mit der dieses Konto zuletzt eingelesen wurde."""
|
||||
client = _fremd()
|
||||
konto = _konto(admin, name="Handykonto", currency="CHF")
|
||||
marke = _marke(admin, konto["id"])
|
||||
kopf = {"X-Certain-Token": marke["token"]}
|
||||
import io
|
||||
|
||||
csv_text = KOPF + "01.04.2026;-12,00;Bäckerei;Brot;\n02.04.2026;-8,00;Kiosk;Zeitung;\n"
|
||||
|
||||
# Ohne vorherigen Import am Rechner: klare Ansage statt Rätselraten.
|
||||
r = client.post("/api/quick/statement",
|
||||
files={"file": ("a.csv", io.BytesIO(csv_text.encode()), "text/csv")},
|
||||
data={"account_id": str(konto["id"])}, headers=kopf)
|
||||
assert r.status_code == 400
|
||||
assert "am Rechner" in r.json()["detail"]
|
||||
|
||||
# Einmal am Rechner einlesen legt die Einstellung fest.
|
||||
import json as _json
|
||||
vorlage = admin.post("/api/imports/templates", json={
|
||||
"name": "Handytest " + secrets.token_hex(3), "delimiter": ";", "decimal_sep": ",",
|
||||
"date_format": "%d.%m.%Y", "encoding": "utf-8", "has_header": True, "skip_rows": 0,
|
||||
"amount_mode": "signed",
|
||||
"column_map": {"date": 0, "amount": 1, "payee": 2, "purpose": 3},
|
||||
})
|
||||
assert vorlage.status_code == 201, vorlage.text
|
||||
v = _import(admin, konto["id"], csv_text)
|
||||
admin.post("/api/imports/commit", json={
|
||||
"account_id": konto["id"], "filename": "april.csv",
|
||||
"template_id": vorlage.json()["id"],
|
||||
"rows": [x for x in v["rows"] if x["include"]]})
|
||||
assert admin.get(f"/api/accounts/{konto['id']}").json()["balance_cents"] == 100000 - 2000
|
||||
|
||||
# Ab jetzt geht es vom Telefon: neue Zeilen kommen an, alte nicht doppelt.
|
||||
mehr = csv_text + "03.04.2026;-5,50;Coop;Milch;\n"
|
||||
r = client.post("/api/quick/statement",
|
||||
files={"file": ("april.csv", io.BytesIO(mehr.encode()), "text/csv")},
|
||||
data={"account_id": str(konto["id"])}, headers=kopf)
|
||||
assert r.status_code == 201, r.text
|
||||
assert r.json()["gebucht"] == 1
|
||||
assert r.json()["duplikate"] == 2
|
||||
assert admin.get(f"/api/accounts/{konto['id']}").json()["balance_cents"] == 100000 - 2550
|
||||
|
||||
# Und der Stapel steht im Verlauf, also mit einem Klick ruecknehmbar.
|
||||
stapel = admin.get("/api/imports/batches").json()
|
||||
assert any(b["filename"] == "april.csv" and b["imported_count"] == 1 for b in stapel)
|
||||
|
||||
|
||||
def test_auszug_vom_telefon_braucht_eine_gueltige_marke(admin):
|
||||
import io
|
||||
konto = _konto(admin, name="Fremdes Konto")
|
||||
@@ -305,3 +256,54 @@ def test_auszug_vom_telefon_braucht_eine_gueltige_marke(admin):
|
||||
files={"file": ("a.csv", io.BytesIO(b"x"), "text/csv")},
|
||||
data={"account_id": str(konto["id"])})
|
||||
assert r.status_code == 401
|
||||
|
||||
|
||||
def test_auszug_vom_telefon_wird_nur_abgelegt_nicht_gebucht(admin):
|
||||
"""Am Telefon prüft man keine 500 Zeilen. Die Datei wartet in Certain."""
|
||||
client = _fremd()
|
||||
konto = _konto(admin, name="Ablagekonto", currency="CHF")
|
||||
marke = _marke(admin, konto["id"])
|
||||
import io
|
||||
|
||||
csv_text = KOPF + "01.04.2026;-12,00;Bäckerei;Brot;\n"
|
||||
r = client.post("/api/quick/statement",
|
||||
files={"file": ("april.csv", io.BytesIO(csv_text.encode()), "text/csv")},
|
||||
data={"account_id": str(konto["id"])},
|
||||
headers={"X-Certain-Token": marke["token"]})
|
||||
assert r.status_code == 201, r.text
|
||||
assert "Empfangen" in r.json()["message"]
|
||||
# Nichts gebucht.
|
||||
assert admin.get(f"/api/accounts/{konto['id']}").json()["balance_cents"] == 100000
|
||||
|
||||
wartend = [u for u in admin.get("/api/imports/uploads").json()
|
||||
if u["account_id"] == konto["id"]]
|
||||
assert len(wartend) == 1
|
||||
assert wartend[0]["filename"] == "april.csv"
|
||||
|
||||
# Der Inhalt kommt unverändert zurück – die Import-Ansicht liest ihn wie
|
||||
# eine lokale Datei.
|
||||
inhalt = admin.get(f"/api/imports/uploads/{wartend[0]['id']}/content")
|
||||
assert inhalt.status_code == 200
|
||||
assert "Bäckerei" in inhalt.content.decode("utf-8")
|
||||
|
||||
assert admin.delete(f"/api/imports/uploads/{wartend[0]['id']}").status_code == 204
|
||||
assert not [u for u in admin.get("/api/imports/uploads").json()
|
||||
if u["id"] == wartend[0]["id"]]
|
||||
|
||||
|
||||
def test_leere_und_zu_grosse_dateien_werden_abgewiesen(admin):
|
||||
client = _fremd()
|
||||
konto = _konto(admin, name="Grenzkonto")
|
||||
marke = _marke(admin, konto["id"])
|
||||
kopf = {"X-Certain-Token": marke["token"]}
|
||||
import io
|
||||
|
||||
leer = client.post("/api/quick/statement",
|
||||
files={"file": ("leer.csv", io.BytesIO(b""), "text/csv")},
|
||||
data={"account_id": str(konto["id"])}, headers=kopf)
|
||||
assert leer.status_code == 400
|
||||
|
||||
riesig = client.post("/api/quick/statement",
|
||||
files={"file": ("gross.csv", io.BytesIO(b"x" * (6 * 1024 * 1024)), "text/csv")},
|
||||
data={"account_id": str(konto["id"])}, headers=kopf)
|
||||
assert riesig.status_code == 413
|
||||
|
||||
Reference in New Issue
Block a user