Files
family-hub/backend/app/api/v1/chores.py

106 lines
2.9 KiB
Python

"""Chores API endpoints."""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from datetime import datetime
from app.core.database import get_db
from app.api.v1.auth import get_current_user
from app.models.user import User
from app.models.chore import Chore, ChoreStatus
from app.schemas import chore as chore_schemas
router = APIRouter()
@router.get("", response_model=List[chore_schemas.Chore])
def get_chores(
skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Get all chores."""
chores = db.query(Chore).offset(skip).limit(limit).all()
return chores
@router.get("/{chore_id}", response_model=chore_schemas.Chore)
def get_chore(
chore_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Get a specific chore by ID."""
chore = db.query(Chore).filter(Chore.id == chore_id).first()
if not chore:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Chore not found"
)
return chore
@router.post("", response_model=chore_schemas.Chore, status_code=status.HTTP_201_CREATED)
def create_chore(
chore_in: chore_schemas.ChoreCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Create a new chore."""
chore = Chore(**chore_in.model_dump())
db.add(chore)
db.commit()
db.refresh(chore)
return chore
@router.put("/{chore_id}", response_model=chore_schemas.Chore)
def update_chore(
chore_id: int,
chore_in: chore_schemas.ChoreUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Update a chore."""
chore = db.query(Chore).filter(Chore.id == chore_id).first()
if not chore:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Chore not found"
)
# Update fields
update_data = chore_in.model_dump(exclude_unset=True)
# If status is being changed to completed, set completed_at
if update_data.get("status") == ChoreStatus.COMPLETED and chore.status != ChoreStatus.COMPLETED:
update_data["completed_at"] = datetime.utcnow()
for field, value in update_data.items():
setattr(chore, field, value)
db.commit()
db.refresh(chore)
return chore
@router.delete("/{chore_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_chore(
chore_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Delete a chore."""
chore = db.query(Chore).filter(Chore.id == chore_id).first()
if not chore:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Chore not found"
)
db.delete(chore)
db.commit()
return None