from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.future import select from typing import List, Optional from app.models import Category from app.schemas.category import CategoryCreate, CategoryUpdate async def create_category(db: AsyncSession, category_in: CategoryCreate, user_id: int, group_id: Optional[int] = None) -> Category: db_category = Category(**category_in.dict(), user_id=user_id, group_id=group_id) db.add(db_category) await db.commit() await db.refresh(db_category) return db_category async def get_user_categories(db: AsyncSession, user_id: int) -> List[Category]: result = await db.execute(select(Category).where(Category.user_id == user_id)) return result.scalars().all() async def get_group_categories(db: AsyncSession, group_id: int) -> List[Category]: result = await db.execute(select(Category).where(Category.group_id == group_id)) return result.scalars().all() async def get_category(db: AsyncSession, category_id: int) -> Optional[Category]: return await db.get(Category, category_id) async def update_category(db: AsyncSession, db_category: Category, category_in: CategoryUpdate) -> Category: update_data = category_in.dict(exclude_unset=True) for key, value in update_data.items(): setattr(db_category, key, value) db.add(db_category) await db.commit() await db.refresh(db_category) return db_category async def delete_category(db: AsyncSession, db_category: Category): await db.delete(db_category) await db.commit() return db_category