from datetime import date from typing import Optional from fastapi import APIRouter, Depends, HTTPException from sqlalchemy import select from sqlalchemy.orm import Session from database import get_db from models import OtherPurchase, User from schemas import OtherPurchaseCreate, OtherPurchaseUpdate, OtherPurchaseOut from auth import get_current_user router = APIRouter(prefix="/api/other", tags=["other"]) @router.get("", response_model=list[OtherPurchaseOut]) def list_other_purchases( start: Optional[date] = None, end: Optional[date] = None, db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): q = ( select(OtherPurchase) .where(OtherPurchase.user_id == current_user.id) .order_by(OtherPurchase.date.desc()) ) if start: q = q.where(OtherPurchase.date >= start) if end: q = q.where(OtherPurchase.date <= end) return db.scalars(q).all() @router.post("", response_model=OtherPurchaseOut, status_code=201) def create_other_purchase( body: OtherPurchaseCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): record = OtherPurchase(**body.model_dump(), user_id=current_user.id) db.add(record) db.commit() db.refresh(record) return record @router.put("/{record_id}", response_model=OtherPurchaseOut) def update_other_purchase( record_id: int, body: OtherPurchaseUpdate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): record = db.scalars( select(OtherPurchase) .where(OtherPurchase.id == record_id, OtherPurchase.user_id == current_user.id) ).first() if not record: raise HTTPException(status_code=404, detail="Record not found") for field, value in body.model_dump(exclude_none=True).items(): setattr(record, field, value) db.commit() db.refresh(record) return record @router.delete("/{record_id}", status_code=204) def delete_other_purchase( record_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): record = db.scalars( select(OtherPurchase) .where(OtherPurchase.id == record_id, OtherPurchase.user_id == current_user.id) ).first() if not record: raise HTTPException(status_code=404, detail="Record not found") db.delete(record) db.commit()