diff --git a/backend/app/dependencies.py b/backend/app/dependencies.py index 65815f3..2107d45 100644 --- a/backend/app/dependencies.py +++ b/backend/app/dependencies.py @@ -36,4 +36,9 @@ def get_current_user( detail="Invalid or expired token", ) - return user \ No newline at end of file + return user + +CurrentUserDependency = Annotated[ + User, + Depends(get_current_user), +] \ No newline at end of file diff --git a/backend/app/main.py b/backend/app/main.py index f3f4a00..7ecfb59 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -2,10 +2,12 @@ from app.config import APP_NAME from app.routers.auth import router as auth_router +from app.routers.entries import router as entries_router app = FastAPI(title=APP_NAME) app.include_router(auth_router) +app.include_router(entries_router) @app.get("/health") diff --git a/backend/app/routers/auth.py b/backend/app/routers/auth.py index 311343e..91b3c32 100644 --- a/backend/app/routers/auth.py +++ b/backend/app/routers/auth.py @@ -1,10 +1,8 @@ -from typing import Annotated - -from fastapi import APIRouter, Depends, HTTPException, status +from fastapi import APIRouter, HTTPException, status from sqlmodel import select from app.database import SessionDependency -from app.dependencies import get_current_user +from app.dependencies import CurrentUserDependency from app.models import User from app.schemas.user import UserLogin, UserRegister from app.security import ( @@ -14,11 +12,6 @@ verify_password, ) -CurrentUserDependency = Annotated[ - User, - Depends(get_current_user), -] - router = APIRouter() diff --git a/backend/app/routers/entries.py b/backend/app/routers/entries.py new file mode 100644 index 0000000..63c22d3 --- /dev/null +++ b/backend/app/routers/entries.py @@ -0,0 +1,129 @@ +from fastapi import APIRouter, HTTPException, status +from sqlmodel import Session, select + +from app.database import SessionDependency +from app.dependencies import CurrentUserDependency +from app.models import Entry, User +from app.schemas.entry import EntryCreate, EntryResponse, EntryUpdate + +router = APIRouter( + prefix="/entries", + tags=["entries"], +) + + +def get_own_entry_or_404( + session: Session, + entry_id: int, + current_user: User, +) -> Entry: + entry = session.exec( + select(Entry).where( + Entry.id == entry_id, + Entry.user_id == current_user.id, + ) + ).first() + + if entry is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Entry not found", + ) + + return entry + +@router.post( + "", + response_model=EntryResponse, + status_code=status.HTTP_201_CREATED, +) +def create_entry( + entry_data: EntryCreate, + session: SessionDependency, + current_user: CurrentUserDependency, +): + entry = Entry( + user_id=current_user.id, # ** entpackt Schlüssel und Werte zu benannten Argumenten + **entry_data.model_dump(), # (macht quasi kind = entry_data.kind, amount = entry_data.amount usw.) + ) # z.B. daten ={"kind"= receipt,} entry(**daten) -> entry (kind = receipt) + + session.add(entry) + session.commit() + session.refresh(entry) + + return entry + +@router.get( + "", + response_model=list[EntryResponse], +) +def list_entries( + session: SessionDependency, + current_user: CurrentUserDependency, +): + entries = session.exec( + select(Entry).where(Entry.user_id == current_user.id) + ).all() + + return entries + +@router.get( + "/{entry_id}", + response_model=EntryResponse, +) +def get_entry( + entry_id: int, + session: SessionDependency, + current_user: CurrentUserDependency, +): + return get_own_entry_or_404( + session, + entry_id, + current_user, + ) + +@router.patch( + "/{entry_id}", + response_model=EntryResponse, +) +def update_entry( + entry_id: int, + entry_data: EntryUpdate, + session: SessionDependency, + current_user: CurrentUserDependency, +): + entry = get_own_entry_or_404( + session, + entry_id, + current_user, + ) + + update_data = entry_data.model_dump(exclude_unset=True) #exclude_unset=True gibt nur die vom Client tatsächlich mitgeschickten Felder aus + + for field, value in update_data.items(): + setattr(entry, field, value) + + session.add(entry) + session.commit() + session.refresh(entry) + + return entry + +@router.delete( + "/{entry_id}", + status_code=status.HTTP_204_NO_CONTENT, +) +def delete_entry( + entry_id: int, + session: SessionDependency, + current_user: CurrentUserDependency, +): + entry = get_own_entry_or_404( + session, + entry_id, + current_user, + ) + + session.delete(entry) + session.commit() + \ No newline at end of file diff --git a/backend/app/schemas/entry.py b/backend/app/schemas/entry.py new file mode 100644 index 0000000..ca6de35 --- /dev/null +++ b/backend/app/schemas/entry.py @@ -0,0 +1,51 @@ +from datetime import date, datetime +from typing import Literal + +from pydantic import BaseModel, Field, field_validator + +EntryKind = Literal["receipt", "trip"] + +EntryCategory = Literal[ + "uncategorized", + "work_equipment", + "literature", + "training", + "trips", + "other", +] + +class EntryCreate(BaseModel): + kind: EntryKind = "receipt" + amount: int | None = Field(default=None, ge=0) + entry_date: date = Field(default_factory=date.today) + category: EntryCategory = "uncategorized" + note: str | None = None + distance_km: int | None = Field(default=None, ge=0) + days: int | None = Field(default=None, ge=0) + +class EntryUpdate(BaseModel): + kind: EntryKind | None = None + amount: int | None = Field(default=None, ge=0) + entry_date: date | None = None + category: EntryCategory | None = None + note: str | None = None + distance_km: int | None = Field(default=None, ge=0) + days: int | None = Field(default=None, ge=0) + + @field_validator("kind", "entry_date", "category") + @classmethod + def not_null(cls, value): + if value is None: + raise ValueError("must not be null") + return value + +class EntryResponse(BaseModel): + id: int + kind: EntryKind + amount: int | None + entry_date: date + category: EntryCategory + note: str | None + distance_km: int | None + days: int | None + created_at: datetime \ No newline at end of file diff --git a/backend/tests/test_entries.py b/backend/tests/test_entries.py new file mode 100644 index 0000000..048691c --- /dev/null +++ b/backend/tests/test_entries.py @@ -0,0 +1,466 @@ +import pytest +from fastapi.testclient import TestClient + + +def create_user_and_login(client: TestClient, name: str, email: str) -> str: + password = "sicheresPasswort123" + + register_response = client.post( + "/register", + json={ + "name": name, + "email": email, + "password": password, + }, + ) + + assert register_response.status_code == 201 + + login_response = client.post( + "/login", + json={ + "email": email, + "password": password, + }, + ) + + assert login_response.status_code == 200 + + return login_response.json()["access_token"] + +def test_create_entry(client): + access_token = create_user_and_login(client, "Illia", "illia@example.com") + + response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + "note": "USB-C Adapter", + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert response.status_code == 201 + + data = response.json() + + assert data["id"] is not None + assert data["kind"] == "receipt" + assert data["amount"] == 1999 + assert data["category"] == "work_equipment" + assert data["note"] == "USB-C Adapter" + + assert "user_id" not in data + assert "photo_path" not in data + +def test_create_entry_without_token(client): + response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + }, + ) + + assert response.status_code == 401 + +def test_list_entries_only_returns_own_entries(client): + illia_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + andreas_token = create_user_and_login( + client, + "Andreas", + "andreas@example.com", + ) + + illia_entry = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + "note": "Illias Entry", + }, + headers={ + "Authorization": f"Bearer {illia_token}" + }, + ) + + assert illia_entry.status_code == 201 + + andreas_entry = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 2999, + "category": "literature", + "note": "Andreas Entry", + }, + headers={ + "Authorization": f"Bearer {andreas_token}" + }, + ) + + assert andreas_entry.status_code == 201 + + response = client.get( + "/entries", + headers={ + "Authorization": f"Bearer {illia_token}" + }, + ) + + assert response.status_code == 200 + + entries = response.json() + + assert len(entries) == 1 + assert entries[0]["amount"] == 1999 + assert entries[0]["note"] == "Illias Entry" + +def test_get_own_entry(client: TestClient): + access_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + response = client.get( + f"/entries/{entry_id}", + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert response.status_code == 200 + assert response.json()["id"] == entry_id + assert response.json()["amount"] == 1999 + +def test_get_other_users_entry_returns_404(client: TestClient): + illia_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + andreas_token = create_user_and_login( + client, + "Andreas", + "andreas@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + }, + headers={ + "Authorization": f"Bearer {illia_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + response = client.get( + f"/entries/{entry_id}", + headers={ + "Authorization": f"Bearer {andreas_token}" + }, + ) + + assert response.status_code == 404 + assert response.json() == { + "detail": "Entry not found" + } + +def test_update_own_entry(client: TestClient): + access_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + "note": "Alte Notiz", + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + response = client.patch( + f"/entries/{entry_id}", + json={ + "amount": 2499, + "note": "Neue Notiz", + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert response.status_code == 200 + + data = response.json() + + assert data["amount"] == 2499 + assert data["note"] == "Neue Notiz" + assert data["category"] == "work_equipment" + +def test_update_other_users_entry_returns_404(client: TestClient): + illia_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + andreas_token = create_user_and_login( + client, + "Andreas", + "andreas@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + }, + headers={ + "Authorization": f"Bearer {illia_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + response = client.patch( + f"/entries/{entry_id}", + json={ + "amount": 999999, + }, + headers={ + "Authorization": f"Bearer {andreas_token}" + }, + ) + + assert response.status_code == 404 + assert response.json() == { + "detail": "Entry not found" + } + +def test_delete_own_entry(client: TestClient): + access_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + delete_response = client.delete( + f"/entries/{entry_id}", + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert delete_response.status_code == 204 + + get_response = client.get( + f"/entries/{entry_id}", + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert get_response.status_code == 404 + +def test_delete_other_users_entry_returns_404(client: TestClient): + illia_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + andreas_token = create_user_and_login( + client, + "Andreas", + "andreas@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + }, + headers={ + "Authorization": f"Bearer {illia_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + delete_response = client.delete( + f"/entries/{entry_id}", + headers={ + "Authorization": f"Bearer {andreas_token}" + }, + ) + + assert delete_response.status_code == 404 + + get_response = client.get( + f"/entries/{entry_id}", + headers={ + "Authorization": f"Bearer {illia_token}" + }, + ) + + assert get_response.status_code == 200 + +@pytest.mark.parametrize( + "field", + ["kind", "category", "entry_date"], +) +def test_update_entry_rejects_null_required_fields( + client: TestClient, + field: str, +): + access_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + response = client.patch( + f"/entries/{entry_id}", + json={ + field: None, + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert response.status_code == 422 + +@pytest.mark.parametrize( + "field", + ["amount", "note", "distance_km", "days"], +) +def test_update_entry_allows_null_optional_fields( + client: TestClient, + field: str, +): + access_token = create_user_and_login( + client, + "Illia", + "illia@example.com", + ) + + create_response = client.post( + "/entries", + json={ + "kind": "receipt", + "amount": 1999, + "category": "work_equipment", + "note": "Test", + "distance_km": 20, + "days": 2, + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert create_response.status_code == 201 + + entry_id = create_response.json()["id"] + + response = client.patch( + f"/entries/{entry_id}", + json={ + field: None, + }, + headers={ + "Authorization": f"Bearer {access_token}" + }, + ) + + assert response.status_code == 200 + assert response.json()[field] is None \ No newline at end of file