Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ jobs:
cache-dependency-path: backend/requirements*.txt
- run: python -m pip install -r requirements-dev.txt
- run: python -m ruff check .
- run: python -m ruff format --check .
- run: python -m pytest
mobile:
runs-on: ubuntu-latest
Expand Down
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,15 @@ docker compose run --rm backend alembic upgrade head

Check the new file in `backend/alembic/versions/` before you commit it.

## Formatting the backend

Format the backend code before you commit. CI fails if it is unformatted:

```bash
cd backend
python -m ruff format .
```

## Working on the project

Branches, commits and pull requests: see [docs/git-workflow.md](docs/git-workflow.md).
4 changes: 1 addition & 3 deletions backend/alembic/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,7 @@ def run_migrations_online() -> None:
)

with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
context.configure(connection=connection, target_metadata=target_metadata)

with context.begin_transaction():
context.run_migrations()
Expand Down
58 changes: 33 additions & 25 deletions backend/alembic/versions/4444e762e7e3_create_entries_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
Create Date: 2026-11-19 08:38:22.349963

"""

from collections.abc import Sequence

import sqlalchemy as sa
Expand All @@ -13,43 +14,50 @@
from alembic import op

# revision identifiers, used by Alembic.
revision: str = '4444e762e7e3'
down_revision: str | Sequence[str] | None = 'e48cdf9dee35'
revision: str = "4444e762e7e3"
down_revision: str | Sequence[str] | None = "e48cdf9dee35"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('entries',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('kind', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('amount', sa.Integer(), nullable=True),
sa.Column('entry_date', sa.Date(), nullable=False),
sa.Column('category', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('note', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('photo_path', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('distance_km', sa.Integer(), nullable=True),
sa.Column('days', sa.Integer(), nullable=True),
sa.Column('created_at', sqlmodel.sql.sqltypes.UTCDateTime(), nullable=False),
sa.CheckConstraint("category IN ('uncategorized', 'work_equipment', 'literature', 'training', 'trips', 'other')", name='ck_entries_category'),
sa.CheckConstraint("kind IN ('receipt', 'trip')", name='ck_entries_kind'),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
op.create_table(
"entries",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("kind", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("amount", sa.Integer(), nullable=True),
sa.Column("entry_date", sa.Date(), nullable=False),
sa.Column("category", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("note", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column("photo_path", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column("distance_km", sa.Integer(), nullable=True),
sa.Column("days", sa.Integer(), nullable=True),
sa.Column("created_at", sqlmodel.sql.sqltypes.UTCDateTime(), nullable=False),
sa.CheckConstraint(
"category IN ('uncategorized', 'work_equipment', 'literature', 'training', 'trips', 'other')",
name="ck_entries_category",
),
sa.CheckConstraint("kind IN ('receipt', 'trip')", name="ck_entries_kind"),
sa.ForeignKeyConstraint(
["user_id"],
["users.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f('ix_entries_category'), 'entries', ['category'], unique=False)
op.create_index(op.f('ix_entries_kind'), 'entries', ['kind'], unique=False)
op.create_index(op.f('ix_entries_user_id'), 'entries', ['user_id'], unique=False)
op.create_index(op.f("ix_entries_category"), "entries", ["category"], unique=False)
op.create_index(op.f("ix_entries_kind"), "entries", ["kind"], unique=False)
op.create_index(op.f("ix_entries_user_id"), "entries", ["user_id"], unique=False)
# ### end Alembic commands ###


def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_entries_user_id'), table_name='entries')
op.drop_index(op.f('ix_entries_kind'), table_name='entries')
op.drop_index(op.f('ix_entries_category'), table_name='entries')
op.drop_table('entries')
op.drop_index(op.f("ix_entries_user_id"), table_name="entries")
op.drop_index(op.f("ix_entries_kind"), table_name="entries")
op.drop_index(op.f("ix_entries_category"), table_name="entries")
op.drop_table("entries")
# ### end Alembic commands ###
26 changes: 14 additions & 12 deletions backend/alembic/versions/e48cdf9dee35_create_users_table.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""create users table

Revision ID: e48cdf9dee35
Revises:
Revises:
Create Date: 2026-11-11 12:43:02.418363

"""

from collections.abc import Sequence

import sqlalchemy as sa
Expand All @@ -13,7 +14,7 @@
from alembic import op

# revision identifiers, used by Alembic.
revision: str = 'e48cdf9dee35'
revision: str = "e48cdf9dee35"
down_revision: str | Sequence[str] | None = None
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
Expand All @@ -22,21 +23,22 @@
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('email', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('password_hash', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('created_at', sqlmodel.sql.sqltypes.UTCDateTime(), nullable=False),
sa.PrimaryKeyConstraint('id')
op.create_table(
"users",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("email", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("password_hash", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("created_at", sqlmodel.sql.sqltypes.UTCDateTime(), nullable=False),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
op.create_index(op.f("ix_users_email"), "users", ["email"], unique=True)
# ### end Alembic commands ###


def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_users_email'), table_name='users')
op.drop_table('users')
op.drop_index(op.f("ix_users_email"), table_name="users")
op.drop_table("users")
# ### end Alembic commands ###
4 changes: 1 addition & 3 deletions backend/app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@
JWT_SECRET = os.getenv("JWT_SECRET")

if not JWT_SECRET or len(JWT_SECRET) < 32:
raise RuntimeError(
"JWT_SECRET must be set and contain at least 32 characters"
)
raise RuntimeError("JWT_SECRET must be set and contain at least 32 characters")

JWT_ALGORITHM = os.getenv("JWT_ALGORITHM", "HS256")
JWT_EXPIRE_MINUTES = int(os.getenv("JWT_EXPIRE_MINUTES", "30"))
3 changes: 2 additions & 1 deletion backend/app/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ def get_current_user(

return user


CurrentUserDependency = Annotated[
User,
Depends(get_current_user),
]
]
1 change: 0 additions & 1 deletion backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,3 @@
@app.get("/health")
def health():
return {"status": "ok"}

2 changes: 1 addition & 1 deletion backend/app/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .entry import Entry
from .user import User

__all__ = ["Entry", "User"]
__all__ = ["Entry", "User"]
5 changes: 4 additions & 1 deletion backend/app/models/entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ class Entry(SQLModel, table=True):
__tablename__ = "entries"
__table_args__ = (
CheckConstraint("kind IN ('receipt', 'trip')", name="ck_entries_kind"),
CheckConstraint("category IN ('uncategorized', 'work_equipment', 'literature', 'training', 'trips', 'other')", name="ck_entries_category")
CheckConstraint(
"category IN ('uncategorized', 'work_equipment', 'literature', 'training', 'trips', 'other')",
name="ck_entries_category",
),
)

id: int | None = Field(default=None, primary_key=True)
Expand Down
3 changes: 1 addition & 2 deletions backend/app/models/user.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

from datetime import UTC, datetime

from sqlmodel import Field, SQLModel
Expand All @@ -11,4 +10,4 @@ class User(SQLModel, table=True):
name: str = Field()
email: str = Field(index=True, unique=True)
password_hash: str
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
12 changes: 5 additions & 7 deletions backend/app/routers/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@

@router.post("/register", status_code=status.HTTP_201_CREATED)
def register(user: UserRegister, session: SessionDependency):
existing_user = session.exec(
select(User).where(User.email == user.email)
).first()
existing_user = session.exec(select(User).where(User.email == user.email)).first()

if existing_user:
raise HTTPException(
Expand All @@ -43,11 +41,10 @@ def register(user: UserRegister, session: SessionDependency):
"email": new_user.email,
}


@router.post("/login")
def login(user: UserLogin, session: SessionDependency):
existing_user = session.exec(
select(User).where(User.email == user.email)
).first()
existing_user = session.exec(select(User).where(User.email == user.email)).first()

if existing_user is not None:
password_hash_to_check = existing_user.password_hash
Expand All @@ -72,10 +69,11 @@ def login(user: UserLogin, session: SessionDependency):
"token_type": "bearer",
}


@router.get("/me")
def get_me(current_user: CurrentUserDependency):
return {
"id": current_user.id,
"name": current_user.name,
"email": current_user.email,
}
}
22 changes: 13 additions & 9 deletions backend/app/routers/entries.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def get_own_entry_or_404(

return entry


@router.post(
"",
response_model=EntryResponse,
Expand All @@ -43,16 +44,17 @@ def create_entry(
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)
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],
Expand All @@ -61,12 +63,11 @@ def list_entries(
session: SessionDependency,
current_user: CurrentUserDependency,
):
entries = session.exec(
select(Entry).where(Entry.user_id == current_user.id)
).all()
entries = session.exec(select(Entry).where(Entry.user_id == current_user.id)).all()

return entries


@router.get(
"/{entry_id}",
response_model=EntryResponse,
Expand All @@ -82,6 +83,7 @@ def get_entry(
current_user,
)


@router.patch(
"/{entry_id}",
response_model=EntryResponse,
Expand All @@ -98,7 +100,9 @@ def update_entry(
current_user,
)

update_data = entry_data.model_dump(exclude_unset=True) #exclude_unset=True gibt nur die vom Client tatsächlich mitgeschickten Felder aus
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)
Expand All @@ -109,6 +113,7 @@ def update_entry(

return entry


@router.delete(
"/{entry_id}",
status_code=status.HTTP_204_NO_CONTENT,
Expand All @@ -126,4 +131,3 @@ def delete_entry(

session.delete(entry)
session.commit()

17 changes: 10 additions & 7 deletions backend/app/schemas/entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
EntryKind = Literal["receipt", "trip"]

EntryCategory = Literal[
"uncategorized",
"work_equipment",
"literature",
"training",
"trips",
"other",
"uncategorized",
"work_equipment",
"literature",
"training",
"trips",
"other",
]


class EntryCreate(BaseModel):
kind: EntryKind = "receipt"
amount: int | None = Field(default=None, ge=0)
Expand All @@ -23,6 +24,7 @@ class EntryCreate(BaseModel):
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)
Expand All @@ -39,6 +41,7 @@ def not_null(cls, value):
raise ValueError("must not be null")
return value


class EntryResponse(BaseModel):
id: int
kind: EntryKind
Expand All @@ -48,4 +51,4 @@ class EntryResponse(BaseModel):
note: str | None
distance_km: int | None
days: int | None
created_at: datetime
created_at: datetime
Loading
Loading