Smart Budget Advisory
Relevant source files
The following files were used as context for generating this wiki page:
- app/src/main/java/io/github/mojri/hesabyar/api/BudgetAdvisor.kt
- app/src/main/java/io/github/mojri/hesabyar/api/BudgetAdviceGenerator.kt
- rust/hesabyar-core/src/advisory/budget.rs
- rust/hesabyar-core/src/ai_validation.rs
- app/src/main/java/io/github/mojri/hesabyar/rust/RustBridge.kt
- app/src/main/java/io/github/mojri/hesabyar/ui/AiAssistantViewModel.kt
The Smart Budget Advisory system is a multi-layered financial intelligence module within Hesabyar that provides personalized financial insights, budget forecasts, and health scoring. It operates in two primary modes: a cloud-based AI mode (utilizing providers like Gemini or OpenRouter) for deep linguistic analysis and a high-performance offline mode powered by a shared Rust core (hesabyar-core).
The system processes a user's financial ledger—including transactions, loans, and installments—to generate actionable advice. It is designed with an "offline-first" philosophy, ensuring that even without internet connectivity or AI configuration, users receive data-driven local analysis.
Sources: README.md, app/src/main/java/io/github/mojri/hesabyar/api/BudgetAdvisor.kt:33-46, app/src/main/java/io/github/mojri/hesabyar/api/BudgetAdviceGenerator.kt:70-85
Architectural Overview
The advisory system follows a tiered architecture where the Kotlin UI layer communicates with a specialized advisor service, which then delegates to either the AI provider or the native Rust bridge.
Data Flow for Budget Advice
The following diagram illustrates the decision logic and data flow when a user requests budget advice.
The system prioritizes AI analysis if configured, but strictly validates AI output using the Rust native core to ensure technical accuracy and Persian language integrity.
Sources: app/src/main/java/io/github/mojri/hesabyar/api/BudgetAdviceGenerator.kt:76-105, app/src/main/java/io/github/mojri/hesabyar/rust/RustBridge.kt:120-130
Core Components
1. Budget Advice Generator
This internal module handles the construction of the "Data Summary" sent to AI providers. It aggregates transactions, calculates totals (Income vs. Expense), and appends active debt obligations (loans and installments) to provide the AI with full context.
| Feature | Implementation |
|---|---|
| Data Summary | Formats transaction counts, Toman totals, and category breakdowns. |
| Offline Fallback | Provides rule-based advice when AI is unavailable. |
| Rial-to-Toman | Converts DB values (Rial) to user-friendly Toman (Factor: 10). |
Sources: app/src/main/java/io/github/mojri/hesabyar/api/BudgetAdviceGenerator.kt:107-160
2. Native Advisory Engine (Rust)
The hesabyar-core library provides the high-performance logic for offline advice and forecasting. It uses a trailing 90-day window to calculate an "income baseline," ensuring that debt-to-income ratios reflect current financial capacity rather than all-time historical data.
// Calculation of monthly income baseline in Rust core
fn monthly_income_baseline(transactions: &[Transaction], now_ms: i64) -> i64 {
let window_start = now_ms - 90 * 24 * 60 * 60 * 1000;
let recent: Vec<&Transaction> = transactions.iter()
.filter(|t| t.tx_type == TransactionType::Income && t.date >= window_start)
.collect();
// ... normalization logic ...
}
Sources: rust/hesabyar-core/src/advisory/budget.rs:114-132
Financial Metrics & Forecasting
The system calculates several key performance indicators (KPIs) to determine financial health.
Debt-to-Income Ratio
Calculated by summing monthly debt payments (unpaid installments + 1/12th of creditor loans) and dividing by the monthly income baseline.
- Target: A ratio > 0.4 triggers high-risk warnings in the UI.
- Formula:
(Monthly Installments + (Remaining Creditor Loan / 12)) / Monthly Income
Sources: app/src/main/java/io/github/mojri/hesabyar/api/BudgetAdvisor.kt:233-248, rust/hesabyar-core/src/advisory/budget.rs:135-154
Financial Health Score
A weighted score from 0 to 100 based on three primary factors derived from the Rust core:
- Savings Rate (Max +25): Bonus points for rates >= 30%.
- Debt-to-Income (Max +15): Bonus points for ratios <= 10%.
- Category Diversification (Max +10): Awarded for spending across 3 or more categories.
Sources: rust/hesabyar-core/src/advisory/budget.rs:188-245, app/src/main/java/io/github/mojri/hesabyar/api/BudgetAdvisor.kt:294-345
AI Validation & Sanitization
To ensure security and reliability, all AI-generated content passes through a native Rust validation pipeline before being displayed to the user.
Validation Policy
- Minimum Length: Rejects text under 10 characters.
- Maximum Length: Truncates text exceeding 10,000 characters.
- Sanitization: Strips dangerous Markdown/HTML patterns like
<script>orjavascript:. - Linguistic Check: Issues a warning if no Persian characters are detected.
Sources: rust/hesabyar-core/src/ai_validation.rs:248-316, app/src/main/java/io/github/mojri/hesabyar/rust/RustBridge.kt:120-141
Budget Forecasting
The system provides a 30-day "Smart Forecast" that projects the user's cash balance.
Forecasting Logic
- Historical Average: Calculates average monthly income/expense over the last 90 days.
- Obligation Tracking: Identifies all unpaid installments due within the next 30 days.
- Surplus/Deficit Prediction: Subtracts obligations from the estimated balance.
- Smart Alerts: Generates a "Risk" alert if the projected balance is negative.
Sources: rust/hesabyar-core/src/advisory/budget.rs:65-110, app/src/main/java/io/github/mojri/hesabyar/api/BudgetAdvisor.kt:127-185
Conclusion
Smart Budget Advisory serves as a critical bridge between raw financial data and user action. By combining the linguistic capabilities of LLMs with the deterministic accuracy of a Rust-based financial engine, Hesabyar provides reliable, privacy-preserving, and offline-capable financial guidance tailored to the Persian-speaking user base.