раскидал структуру для монорепозитория

This commit is contained in:
arrelin
2025-12-09 18:31:45 +03:00
parent 7e1e89424a
commit aadbc099b0
48 changed files with 4048 additions and 5 deletions

View File

@@ -0,0 +1,95 @@
use sea_orm::*;
use sea_orm::prelude::Decimal;
use chrono::Utc;
use crate::models::expense::{self, Entity as Expense, Model as ExpenseModel};
use crate::models::category::{Entity as Category};
pub struct ExpenseService;
impl ExpenseService {
pub async fn create(
db: &DatabaseConnection,
category_id: i32,
amount: Decimal,
description: Option<String>,
) -> Result<ExpenseModel, DbErr> {
let expense = expense::ActiveModel {
category_id: Set(category_id),
amount: Set(amount),
description: Set(description),
created_at: Set(Utc::now().naive_utc()),
..Default::default()
};
expense.insert(db).await
}
pub async fn find_by_id(db: &DatabaseConnection, id: i32) -> Result<Option<ExpenseModel>, DbErr> {
Expense::find_by_id(id).one(db).await
}
pub async fn find_all(db: &DatabaseConnection) -> Result<Vec<ExpenseModel>, DbErr> {
Expense::find().all(db).await
}
pub async fn find_by_category_id(
db: &DatabaseConnection,
category_id: i32,
) -> Result<Vec<ExpenseModel>, DbErr> {
Expense::find()
.filter(expense::Column::CategoryId.eq(category_id))
.all(db)
.await
}
pub async fn update(
db: &DatabaseConnection,
id: i32,
amount: Option<Decimal>,
description: Option<String>,
) -> Result<ExpenseModel, DbErr> {
let expense = Expense::find_by_id(id)
.one(db)
.await?
.ok_or(DbErr::RecordNotFound("Expense not found".to_string()))?;
let mut expense: expense::ActiveModel = expense.into();
if let Some(amount) = amount {
expense.amount = Set(amount);
}
if let Some(desc) = description {
expense.description = Set(Some(desc));
}
expense.update(db).await
}
pub async fn delete(db: &DatabaseConnection, id: i32) -> Result<DeleteResult, DbErr> {
let expense = Expense::find_by_id(id)
.one(db)
.await?
.ok_or(DbErr::RecordNotFound("Expense not found".to_string()))?;
let expense: expense::ActiveModel = expense.into();
expense.delete(db).await
}
pub async fn calculate_remaining_limit(
db: &DatabaseConnection,
category_id: i32,
) -> Result<Decimal, DbErr> {
let category = Category::find_by_id(category_id)
.one(db)
.await?
.ok_or(DbErr::RecordNotFound("Category not found".to_string()))?;
let expenses = Self::find_by_category_id(db, category_id).await?;
let total_spent: Decimal = expenses.iter().map(|e| e.amount).sum();
let remaining = category.limit_amount - total_spent;
Ok(remaining)
}
}