first ruggedy draft
This commit is contained in:
66
apps/api/mousehold_api/routers/accounts.py
Normal file
66
apps/api/mousehold_api/routers/accounts.py
Normal file
@@ -0,0 +1,66 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import models
|
||||
from ..db import get_session
|
||||
from ..schemas import AccountCreate, AccountRead, AccountUpdate
|
||||
|
||||
router = APIRouter(tags=["accounts"])
|
||||
|
||||
|
||||
@router.post("/accounts", response_model=AccountRead)
|
||||
def create_account(
|
||||
payload: AccountCreate, session: Session = Depends(get_session)
|
||||
) -> models.Account:
|
||||
if not session.get(models.Household, payload.household_id):
|
||||
raise HTTPException(status_code=404, detail="Household not found")
|
||||
account = models.Account(**payload.model_dump())
|
||||
session.add(account)
|
||||
session.commit()
|
||||
session.refresh(account)
|
||||
return account
|
||||
|
||||
|
||||
@router.get("/accounts", response_model=list[AccountRead])
|
||||
def list_accounts(
|
||||
household_id: str, session: Session = Depends(get_session)
|
||||
) -> list[models.Account]:
|
||||
return list(
|
||||
session.scalars(
|
||||
select(models.Account)
|
||||
.where(models.Account.household_id == household_id)
|
||||
.order_by(models.Account.name)
|
||||
).all()
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/accounts/{account_id}", response_model=AccountRead)
|
||||
def update_account(
|
||||
account_id: str,
|
||||
payload: AccountUpdate,
|
||||
session: Session = Depends(get_session),
|
||||
) -> models.Account:
|
||||
account = session.get(models.Account, account_id)
|
||||
if not account:
|
||||
raise HTTPException(status_code=404, detail="Account not found")
|
||||
for field, value in payload.model_dump(exclude_unset=True).items():
|
||||
if field == "currency" and value is not None:
|
||||
value = value.upper()
|
||||
setattr(account, field, value)
|
||||
session.add(account)
|
||||
session.commit()
|
||||
session.refresh(account)
|
||||
return account
|
||||
|
||||
|
||||
@router.delete("/accounts/{account_id}")
|
||||
def delete_account(account_id: str, session: Session = Depends(get_session)) -> dict[str, bool]:
|
||||
account = session.get(models.Account, account_id)
|
||||
if not account:
|
||||
raise HTTPException(status_code=404, detail="Account not found")
|
||||
session.delete(account)
|
||||
session.commit()
|
||||
return {"deleted": True}
|
||||
Reference in New Issue
Block a user