use sea_orm::*; use sea_orm::prelude::Decimal; use chrono::Utc; use crate::models::category::{self, Entity as Category, Model as CategoryModel}; pub struct CategoryService; impl CategoryService { pub async fn create( db: &DatabaseConnection, family_id: i32, name: String, limit_amount: Decimal, ) -> Result { let category = category::ActiveModel { family_id: Set(family_id), name: Set(name), limit_amount: Set(limit_amount), created_at: Set(Utc::now().naive_utc()), ..Default::default() }; category.insert(db).await } pub async fn find_by_id(db: &DatabaseConnection, id: i32) -> Result, DbErr> { Category::find_by_id(id).one(db).await } pub async fn find_all(db: &DatabaseConnection) -> Result, DbErr> { Category::find().all(db).await } pub async fn find_by_family_id( db: &DatabaseConnection, family_id: i32, ) -> Result, DbErr> { Category::find() .filter(category::Column::FamilyId.eq(family_id)) .all(db) .await } pub async fn update( db: &DatabaseConnection, id: i32, name: Option, limit_amount: Option, ) -> Result { let category = Category::find_by_id(id) .one(db) .await? .ok_or(DbErr::RecordNotFound("Category not found".to_string()))?; let mut category: category::ActiveModel = category.into(); if let Some(name) = name { category.name = Set(name); } if let Some(limit_amount) = limit_amount { category.limit_amount = Set(limit_amount); } category.update(db).await } pub async fn delete(db: &DatabaseConnection, id: i32) -> Result { let category = Category::find_by_id(id) .one(db) .await? .ok_or(DbErr::RecordNotFound("Category not found".to_string()))?; let category: category::ActiveModel = category.into(); category.delete(db).await } }