api/app/services/plan_service.py

77 lines
2.1 KiB
Python

from datetime import datetime
from fastapi import HTTPException, status
from sqlalchemy.orm import Session
from app.models.plan import Plan
from app.schemas.plan import PlanCreate, PlanToggleStatus, PlanUpdate
def get_plan_list(db: Session, is_active: bool = None):
query = db.query(Plan).filter(Plan.deleted_at.is_(None))
if is_active is not None:
query = query.filter(Plan.is_active == is_active)
return query.order_by(Plan.created_at.desc()).all()
def get_plan_by_id(db: Session, id: str):
plan = db.query(Plan).filter(Plan.id == id, Plan.deleted_at.is_(None)).first()
if not plan:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={"message": "The item does not exist"},
)
return plan
def create_plan(db: Session, data: PlanCreate):
plan = Plan(**data.model_dump())
db.add(plan)
db.commit()
db.refresh(plan)
return plan
def update_plan(db: Session, id: str, data: PlanUpdate):
plan = db.query(Plan).filter(Plan.id == id, Plan.deleted_at.is_(None)).first()
if not plan:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={"message": "The item does not exist"},
)
update_data = data.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(plan, field, value)
db.commit()
db.refresh(plan)
return plan
def delete_plan(db: Session, id: str):
plan = db.query(Plan).filter(Plan.id == id, Plan.deleted_at.is_(None)).first()
if not plan:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={"message": "The item does not exist"},
)
plan.deleted_at = datetime.now()
db.commit()
def toggle_plan_status(db: Session, id: str, data: PlanToggleStatus):
plan = db.query(Plan).filter(Plan.id == id, Plan.deleted_at.is_(None)).first()
if not plan:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={"message": "The item does not exist"},
)
plan.is_active = data.is_active
db.commit()
db.refresh(plan)
return plan