Mini Kabibi Habibi

Current Path : C:/Users/Public/Documents/DXperience 13.1 Demos/ASP.NET/CS/MoneyMonkey/App_Code/
Upload File :
Current File : C:/Users/Public/Documents/DXperience 13.1 Demos/ASP.NET/CS/MoneyMonkey/App_Code/DataProvider.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Data.Linq;
using System.Globalization;
using System.Collections;
using System.Configuration;

public class DataProvider {
    const string DataProviderSessionKey = "DataProvider";
    static IDictionary Context { get { return HttpContext.Current.Items; } }
    public static DataProvider Instance {
        get {
            if(Context[DataProviderSessionKey] == null)
                Context[DataProviderSessionKey] = new DataProvider();
            return (DataProvider)Context[DataProviderSessionKey];
        }
    }

    static bool? _isReadOnly;
    public static bool IsReadOnly {
        get {
            if(!_isReadOnly.HasValue) {
                _isReadOnly = ConfigurationManager.AppSettings["SiteMode"].Equals("true", StringComparison.InvariantCultureIgnoreCase);
            }
            return _isReadOnly.Value;
        }
    }

    DataProvider() {
        DataContext = new DataClassesDataContext();
    }

    public DateTime CurrentDate {
        get {
            return DateTime.Now;
        }
    }

    public DataClassesDataContext DataContext { get; protected set; }

    public IEnumerable<BudgetCategory> SelectBudgets(bool overViewOnly = false) {
        return
            from category in DataContext.BudgetCategories
            where category.UsedInBudget &&
            (!overViewOnly || category.ShowInOverview)
            orderby category.Title
            select category;
    }

    public IEnumerable<BudgetCategory> GetSpreadingExpenses(int take = 0, bool orderByTotal = true) {
        return GetSpreading(BudgetCategoryType.Expenses, take, orderByTotal);
    }
    public IEnumerable<BudgetCategory> GetSpreadingIncome(int take = 0, bool orderByTotal = true) {
        return GetSpreading(BudgetCategoryType.Income, take, orderByTotal);

    }
    public IEnumerable<BudgetCategory> GetSpreadingBusiness(int take = 0, bool orderByTotal = true) {
        return GetSpreading(BudgetCategoryType.Business, take, orderByTotal);
    }
    IEnumerable<BudgetCategory> GetSpreading(BudgetCategoryType categoryType, int take, bool orderByTotal) {
        var query = (
            from category in DataContext.BudgetCategories
            where category.Type == categoryType
            select category).ToList();
        return take > 0 ? query.OrderBy(c => c.TotalAmount).Take(take) : query;
    }

    public decimal GetCurrentMonthlyIncome() {
        var transactions = (from transaction in DataContext.Transactions
                            where transaction.Amount > 0 &&
                            transaction.Date.Month == CurrentDate.Month &&
                            transaction.Date.Year == CurrentDate.Year
                            select transaction.Amount);
        return transactions.Any() ? transactions.Sum() : 0;
    }
    public decimal GetCurrentMonthlySpent() {
        return GetMonthlySpent(DateTime.Now);
    }
    public decimal GetCurrentMonthToPreviousMonthSpent() {
        decimal prevMonthSpent = GetMonthlySpent(DateTime.Now.AddMonths(-1));
        decimal currentMonthSpent = GetMonthlySpent(DateTime.Now);
        return (currentMonthSpent / prevMonthSpent);
    }
    public IEnumerable<Account> GetAccounts() {
        return (from accounts in DataContext.Accounts
                select accounts).ToList();
    }
    public decimal GetAvailableAmount() {
        return DataContext.Transactions.Sum(t => t.Amount);
    }

    public IEnumerable<UpcomingBill> SelectMonthlyUpcomingBills() {
        List<UpcomingBill> monthlyBills = new List<UpcomingBill>();

        var last = new DateTime(CurrentDate.Year, CurrentDate.Month, 1).AddMonths(1).AddDays(-1);
        var bills =
            from bill in DataContext.UpcomingBills
            where
                (bill.Date >= CurrentDate && bill.Date < last) || // is bill finished
                (bill.RepeatType != UpcomingBillRepeatType.NoRepeat && bill.Date < last)
            select bill;

        foreach(var bill in bills) {
            if(bill.Date.Year == CurrentDate.Year && bill.Date.DayOfYear == CurrentDate.DayOfYear) {
                monthlyBills.Add(bill);
                continue;
            }
            switch(bill.RepeatType) {
                case UpcomingBillRepeatType.NoRepeat:
                    if(bill.Date.Year == CurrentDate.Year && bill.Date.Month == CurrentDate.Month && bill.Date >= CurrentDate)
                        monthlyBills.Add(bill);
                    break;
                case UpcomingBillRepeatType.Month:
                    if(bill.Date.Day >= CurrentDate.Day)
                        monthlyBills.Add(bill);
                    break;
                case UpcomingBillRepeatType.Year:
                    if(bill.Date.Month == CurrentDate.Month && bill.Date.Day >= CurrentDate.Day)
                        monthlyBills.Add(bill);
                    break;
            }
        }
        return monthlyBills;
    }
    public decimal GetSpentToBudget() {
        decimal planned = 0;
        decimal spent = 0;
        foreach(var bc in GetBudgets()) {
            if(bc.Amount.HasValue && bc.Amount > 0) {
                planned += bc.Amount.Value;
                spent += bc.CurrentMonthAmount;
            }
        }
        return planned == 0 ? 0 : spent / planned;
    }

    decimal GetMonthlySpent(DateTime date) {
        var transactions = (from transaction in DataContext.Transactions
                            where transaction.Amount < 0 &&
                            transaction.Date.Month == date.Month &&
                            transaction.Date.Year == date.Year
                            select transaction.Amount);
        return transactions.Any() ? transactions.Sum() * -1 : 0;
    }

    public IEnumerable<BudgetCategory> GetBudgets() {
        return
            from budget in DataContext.BudgetCategories
            where budget.UsedInBudget
            orderby budget.Title
            select budget;
    }

    public DateTime GetNearestDateInThisMonth(UpcomingBillRepeatType repeateType, DateTime date) {
        switch(repeateType) {
            case UpcomingBillRepeatType.NoRepeat:
                return date;
            case UpcomingBillRepeatType.Month:
            case UpcomingBillRepeatType.Year:
                return new DateTime(CurrentDate.Year, CurrentDate.Month, date.Day);
        }
        return DateTime.MinValue;
    }

    public IEnumerable<BudgetCategory> SelectNonBudgetCategories() {
        return 
            from category in DataContext.BudgetCategories
            where !category.UsedInBudget && category.Type == BudgetCategoryType.Expenses
            select category;
    }
    public void AddCategoryToBudget(int categoryID) {
        var category = DataContext.BudgetCategories.FirstOrDefault(bc => bc.ID == categoryID);
        if(category != null)
            category.UsedInBudget = true;
        DataContext.SubmitChanges();
    }
}

public static class CurrencyHelper {
    public static readonly NumberFormatInfo CurrencyFormat = CreateCurrencyFormat();
    static NumberFormatInfo CreateCurrencyFormat() {
        var usCulture = CultureInfo.CreateSpecificCulture("en-US");
        var clonedNumbers = (NumberFormatInfo)usCulture.NumberFormat.Clone();
        clonedNumbers.CurrencyNegativePattern = 1;
        return clonedNumbers;
    }
    public static string AsCurrency(this decimal amount) {
        return amount.ToString("c", CurrencyFormat);
    }
}

public partial class BudgetCategory {
    public decimal TotalAmount {
        get {
            var transactions = (
                from transaction in Transactions
                select transaction
            );
            return Math.Abs((transactions.Any() ? transactions.Sum(t => t.Amount) : 0));
        }
    }
    public decimal CurrentMonthAmount {
        get {
            var transactions = (
                from transaction in Transactions
                where transaction.Date.Month == DateTime.Now.Month &&
                transaction.Date.Year == DateTime.Now.Year
                select transaction
            );
            return Math.Abs((transactions.Any() ? transactions.Sum(t => t.Amount) : 0));
        }
    }

    public int SpentAmountPercent {
        get {
            if(!IsActiveBudget)
                return 0;
            return Decimal.ToInt32((CurrentMonthAmount / Math.Abs(Amount.Value)) * 100);
        }
    }

    public bool IsActiveBudget {
        get { return UsedInBudget && Amount.HasValue && Amount.Value > 0; }
    }
}

public partial class UpcomingBill {
    public DateTime NearestBillDate {
        get {
            return DataProvider.Instance.GetNearestDateInThisMonth(RepeatType, Date);
        }
    }
}