Initial commit
This commit is contained in:
77
src/services/category_service.rs
Normal file
77
src/services/category_service.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
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<CategoryModel, DbErr> {
|
||||
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<Option<CategoryModel>, DbErr> {
|
||||
Category::find_by_id(id).one(db).await
|
||||
}
|
||||
|
||||
pub async fn find_all(db: &DatabaseConnection) -> Result<Vec<CategoryModel>, DbErr> {
|
||||
Category::find().all(db).await
|
||||
}
|
||||
|
||||
pub async fn find_by_family_id(
|
||||
db: &DatabaseConnection,
|
||||
family_id: i32,
|
||||
) -> Result<Vec<CategoryModel>, DbErr> {
|
||||
Category::find()
|
||||
.filter(category::Column::FamilyId.eq(family_id))
|
||||
.all(db)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn update(
|
||||
db: &DatabaseConnection,
|
||||
id: i32,
|
||||
name: Option<String>,
|
||||
limit_amount: Option<Decimal>,
|
||||
) -> Result<CategoryModel, DbErr> {
|
||||
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<DeleteResult, DbErr> {
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user