예제 #1
0
 public static BudgetBalance Create(BudgetId budgetId)
 {
     return(new BudgetBalance()
     {
         BudgetId = budgetId
     });
 }
예제 #2
0
 /// <summary>
 /// Initialises a new instance of the <see cref="BudgetListItem"/> class.
 /// </summary>
 /// <param name="budgetId">Budget id</param>
 /// <param name="name">Account name</param>
 /// <param name="currencyCode">Currency code</param>
 /// <param name="accountList">Account list</param>
 /// <param name="commandBus">Command bus</param>
 public BudgetListItem(BudgetId budgetId, string name, string currencyCode, AccountList accountList, ICommandBus commandBus)
 {
     this.budgetId     = budgetId;
     this.name         = name;
     this.currencyCode = currencyCode;
     this.accountList  = accountList;
     this.commandBus   = commandBus;
 }
예제 #3
0
        public virtual ActionResult Create()
        {
            var model = new CreateBudgetViewModel
            {
                Id         = BudgetId.Create().ToString(),
                Name       = "New Budget",
                Currencies = MyBudget.Domain.ValueObjects.Currencies.GetAll(),
            };

            return(View(model));
        }
예제 #4
0
        /// <summary>
        /// Get the initialised account list for a budget
        /// </summary>
        /// <param name="budgetId">Budget id</param>
        /// <returns>Initialised account list</returns>
        private AccountList GetAccountListForBudget(BudgetId budgetId)
        {
            var accountList = this.GetBudgetList().FirstOrDefault(x => budgetId.Equals(x.BudgetId)).Accounts;

            if (accountList == null)
            {
                accountList = new AccountList();
                this.accountListRepository.Save(budgetId, accountList);
            }

            return(accountList);
        }
예제 #5
0
        /// <summary>
        /// Retrieve an account list from the repository.
        /// </summary>
        /// <param name="budget">Budget the accounts belong to</param>
        /// <returns>Reference to the account list in the repository. Guaranteed to be not <c>null</c>.</returns>
        public AccountList Find(BudgetId budget)
        {
            var list = this.readStore.Retrieve <AccountList>(budget.ToGuid());

            if (list == null)
            {
                list = new AccountList();
                this.Save(budget, list);
            }

            return(list);
        }
예제 #6
0
        /// <summary>
        /// Get the initialised account list
        /// </summary>
        /// <param name="budgetId">Budget id</param>
        /// <returns>Initialised account list</returns>
        private AccountList GetAccountListForBudget(BudgetId budgetId)
        {
            var accountList = this.accountListRepository.Find(budgetId);

            if (accountList == null)
            {
                accountList = new AccountList();
                this.accountListRepository.Save(budgetId, accountList);
            }

            return(accountList);
        }
예제 #7
0
        public async Task <Domain.ReadModels.BudgetBalance> GetBudgetBalance(BudgetId budgetId, CancellationToken cancellationToken)
        {
            var storedBalance = await _readDb.BudgetBalances.FirstOrDefaultAsync(x => x.BudgetId == budgetId, cancellationToken);

            if (storedBalance == null || storedBalance.UpdateTime.Date.StartOfMonth() != DateTime.Today.StartOfMonth())
            {
                await CalculateBudgetBalance(budgetId, cancellationToken);

                storedBalance = await _readDb.BudgetBalances.FirstOrDefaultAsync(x => x.BudgetId == budgetId, cancellationToken);
            }

            return(storedBalance);
        }
예제 #8
0
        public void be_created()
        {
            var budgetId = BudgetId.Create();
            var ownerId  = UserId.CreateNew();
            var budget   = new Budget();

            budget.Create(budgetId, "name", ownerId, Currencies.Euro().IsoCode);

            var events = budget.GetUncommittedEvents();

            Assert.AreEqual(1, events.Count());
            Assert.IsTrue(events.OfType <BudgetCreated>().Any());
        }
예제 #9
0
파일: Lines.cs 프로젝트: valeriob/MyBudget
        public MyBudget.Commands.UpdateLine PrepareUpdateLine(string userId)
        {
            var expense = new Expense(new Amount(Currencies.Parse(CurrencyISOCode), Amount), Date, Category, Description, DistributionKey);

            return(new MyBudget.Commands.UpdateLine
            {
                UserId = userId,
                BudgetId = BudgetId.ToString(),
                LineId = LineId.ToString(),
                Id = Guid.NewGuid(),
                Timestamp = DateTime.Now,
                Expense = expense,
            });
        }
예제 #10
0
        public IEnumerable <Category> GetBudgetsCategories(BudgetId budgetId)
        {
            if (HasLoaded == false)
            {
                throw new Exception("Not loaded");
            }

            List <Category> categories;

            if (_categories.TryGetValue(budgetId.ToString(), out categories) == false)
            {
                _categories[budgetId.ToString()] = categories = new List <Category>();
            }
            return(categories.OrderBy(d => d.Name));
        }
예제 #11
0
        public virtual ActionResult Details(string id)
        {
            var budgetId   = new BudgetId(id);
            var budget     = ProjectionManager.GetBudgetsList().GetBudgetById(budgetId);
            var categories = ProjectionManager.GetCategories().GetBudgetsCategories(budgetId);

            var model = new BudgetDetailsViewModel
            {
                Budget           = budget,
                Categories       = categories,
                DistributionKeys = budget.GetDistributionKeys(),
            };

            return(View(model));
        }
예제 #12
0
        /// <summary>
        /// Initialises a new instance of the <see cref="CreateNewBudgetViewModel"/> class.
        /// </summary>
        /// <param name="readRepositories">Repositories for read models</param>
        public CreateNewBudgetViewModel(ReadRepositories readRepositories)
        {
            this.currencyList = readRepositories.CurrencyRepository.GetAll();

            this.CreateNewBudget = new RelayCommand(
                () =>
            {
                var budgetId     = new BudgetId(Guid.NewGuid());
                var currencyCode = this.SelectedCurrency?.Code;
                ServiceLocatorWrapper.Current.GetInstance <Kernel>().CommandBus.Submit(new AddBudgetCommand(budgetId, this.Name, currencyCode));

                // TODO: navigate?
            },
                () => !string.IsNullOrWhiteSpace(this.Name) && this.selectedCurrency != null);
        }
예제 #13
0
        public CreateLine ToCreateLine(DateTime timestamp, BudgetId budgetId, string userId, IEnumerable <MyBudget.Projections.Category> categories)
        {
            var category   = Categoria.Trim().Replace((char)160, ' ');
            var categoryId = categories.FirstOrDefault(d => string.Compare(d.Name, category, true) == 0).Id;
            var expense    = new Expense(new Amount(Currencies.Euro(), Spesa), Data, categoryId, Descrizione, DistributionKey);

            return(new CreateLine
            {
                Id = Guid.NewGuid(),
                Timestamp = timestamp,
                BudgetId = budgetId.ToString(),
                LineId = LineId.Create(budgetId).ToString(),
                UserId = userId,
                Expense = expense,
            });
        }
예제 #14
0
        public static CreateLine ToCreateLine(this Movement mov, BudgetId budgetId, string userId, IEnumerable <MyBudget.Projections.Category> categories)
        {
            var category   = mov.Category.Trim().Replace((char)160, ' ');
            var categoryId = categories.FirstOrDefault(d => string.Compare(d.Name, category, true) == 0).Id;

            var expense = new Expense(new Amount(Currencies.Euro(), Convert.ToDecimal(mov.Import)), mov.DateTime, categoryId, mov.ShortDescription);


            return(new CreateLine
            {
                Id = Guid.NewGuid(),
                Timestamp = DateTime.Now,
                BudgetId = budgetId.ToString(),
                LineId = LineId.Create(budgetId).ToString(),
                UserId = userId,
                Expense = expense,
            });
        }
예제 #15
0
        /// <summary>
        /// Initialises a new instance of the <see cref="Account"/> class.
        /// Create a new account
        /// </summary>
        /// <param name="id">Account id</param>
        /// <param name="name">Account name</param>
        /// <param name="budgetId">Budget the account belongs to</param>
        /// <param name="unitOfWork">Unit of work</param>
        internal Account(AccountId id, string name, BudgetId budgetId, IUnitOfWork unitOfWork) : this(id, unitOfWork, false)
        {
            if (id == null || !id.IsValid())
            {
                throw new ArgumentException("Account id must be valid");
            }

            // TODO: value object instead
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("Account name must be valid");
            }

            if (budgetId == null)
            {
                throw new ArgumentNullException();
            }

            this.Apply(new AddedAccount(name, budgetId));
        }
예제 #16
0
        public virtual ActionResult Create(CreateBudgetViewModel model)
        {
            try
            {
                var handler = CommandManager.Create <CreateBudget>();
                handler(new CreateBudget
                {
                    UserId          = GetCurrentUserId().ToString(),
                    BudgetName      = model.Name,
                    BudgetId        = BudgetId.Create().ToString(),
                    CurrencyISOCode = model.CurrencyISOCode,

                    Id        = Guid.NewGuid(),
                    Timestamp = DateTime.Now,
                });

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
예제 #17
0
 /// <summary>
 /// Retrieve a budget list item from the repository.
 /// </summary>
 /// <param name="id">Budget Id</param>
 /// <returns>Reference to the budget list item in the repository, if found. <c>null</c> otherwise.</returns>
 public BudgetListItem Find(BudgetId id)
 {
     return(this.readStore.Retrieve <BudgetListItem>(id.ToGuid()));
 }
예제 #18
0
 /// <summary>
 /// Save the account list, or add it to the repository. Beware: replaces existing account list in repository.
 /// </summary>
 /// <param name="budget">Budget the accounts belong to</param>
 /// <param name="accountList">Account list to save</param>
 internal void Save(BudgetId budget, AccountList accountList)
 {
     this.readStore.Store(budget.ToGuid(), accountList);
 }
예제 #19
0
        public async Task CalculateBudgetBalance(BudgetId budgetId, CancellationToken cancellationToken)
        {
            var currency = (await _writeDb.Budgets.FirstOrDefaultAsync(x => x.BudgetId == budgetId, cancellationToken: cancellationToken)).Currency;

            var incomeCategoryIds = _writeDb.BudgetCategories
                                    .Where(x => x.BudgetId == budgetId && x.BudgetCategoryType == eBudgetCategoryType.Income)
                                    .Select(x => x.BudgetCategoryId);

            var incomeSum = _writeDb.Transactions
                            .Include(x => x.SubTransactions)
                            .Where(x => incomeCategoryIds.Any(s => s == x.BudgetCategoryId))
                            .Sum(x => x.Amount.Amount + x.SubTransactions.Sum(s => s.Amount.Amount));

            var spendingCategoryIds = _writeDb.BudgetCategories
                                      .Where(x => x.BudgetId == budgetId && x.BudgetCategoryType == eBudgetCategoryType.Spending)
                                      .Select(x => x.BudgetCategoryId);

            var spendingSum = _writeDb.Transactions
                              .Include(x => x.SubTransactions)
                              .Where(x => spendingCategoryIds.Any(s => s == x.BudgetCategoryId))
                              .Sum(x => x.Amount.Amount + x.SubTransactions.Sum(s => s.Amount.Amount));

            var savingCategoryIds = _writeDb.BudgetCategories
                                    .Where(x => x.BudgetId == budgetId && x.BudgetCategoryType == eBudgetCategoryType.Saving)
                                    .Select(x => x.BudgetCategoryId);

            var savingSum = _writeDb.Transactions
                            .Include(x => x.SubTransactions)
                            .Where(x => savingCategoryIds.Any(s => s == x.BudgetCategoryId))
                            .Sum(x => x.Amount.Amount + x.SubTransactions.Sum(s => s.Amount.Amount));

            var storedBalance = await _writeDb.BudgetBalances.FirstOrDefaultAsync(x => x.BudgetId == budgetId, cancellationToken);

            if (storedBalance == null)
            {
                storedBalance = BudgetBalance.Create(budgetId);
                _writeDb.BudgetBalances.Add(storedBalance);
            }

            var totalBalance  = new MoneyAmount(currency.CurrencyCode, incomeSum - spendingSum - savingSum);
            var incomeTotal   = new MoneyAmount(currency.CurrencyCode, incomeSum);
            var spendingTotal = new MoneyAmount(currency.CurrencyCode, spendingSum);
            var savingTotal   = new MoneyAmount(currency.CurrencyCode, savingSum);

            var categoriesBudgetedLeftoverTotal = 0m;
            var budgetCategoryIds = _writeDb.BudgetCategories
                                    .Where(x => x.BudgetId == budgetId && x.BudgetCategoryType == eBudgetCategoryType.Spending)
                                    .Select(x => x.BudgetCategoryId)
                                    .ToList();

            foreach (var budgetCategoryId in budgetCategoryIds)
            {
                categoriesBudgetedLeftoverTotal += Math.Max(0, (await GetCategoryBalance(budgetCategoryId, null, null, cancellationToken)).Amount);
            }

            var unassignedFunds = new MoneyAmount(currency.CurrencyCode, totalBalance.Amount - categoriesBudgetedLeftoverTotal);

            storedBalance.Update(totalBalance, unassignedFunds, spendingTotal, incomeTotal, savingTotal);

            await _writeDb.SaveChangesAsync(cancellationToken);
        }
예제 #20
0
 public override int GetHashCode()
 {
     return(BudgetId.GetHashCode());
 }
예제 #21
0
 /// <summary>
 /// Creates a new account
 /// </summary>
 /// <param name="id">Account id</param>
 /// <param name="name">Account name</param>
 /// <param name="budgetId">Budget this account belongs to</param>
 /// <param name="unitOfWork">Current unit of work</param>
 /// <returns>A new account</returns>
 public static Account Create(AccountId id, string name, BudgetId budgetId, IUnitOfWork unitOfWork)
 {
     return(new Account(id, name, budgetId, unitOfWork));
 }
예제 #22
0
 /// <summary>
 /// Initialises a new instance of the <see cref="AddBudgetCommand" /> class.
 /// </summary>
 /// <param name="id">Unique Id of the budget</param>
 /// <param name="name">Name of the budget</param>
 /// <param name="currencyCode">Currency code (e.g. EUR)</param>
 public AddBudgetCommand(BudgetId id, string name, string currencyCode)
 {
     this.Id           = id;
     this.Name         = name;
     this.CurrencyCode = currencyCode;
 }
예제 #23
0
 public Budget GetBudgetById(BudgetId budgetId)
 {
     return(_budgets[budgetId.ToString()]);
 }
예제 #24
0
 /// <summary>Initialises a new instance of the <see cref="AddAccountCommand" /> class.</summary>
 /// <param name="id">Account id</param>
 /// <param name="name">Account name</param>
 /// <param name="budget">Budget the account belongs to</param>
 public AddAccountCommand(AccountId id, string name, BudgetId budget)
 {
     this.Id     = id;
     this.Name   = name;
     this.Budget = budget;
 }
예제 #25
0
 /// <summary>
 /// Initialises a new instance of the <see cref="AddedAccount"/> class.
 /// </summary>
 /// <param name="name">Account name</param>
 /// <param name="budgetId">Budget the account belongs to</param>
 public AddedAccount(string name, BudgetId budgetId)
 {
     this.Name   = name;
     this.Budget = budgetId;
 }
예제 #26
0
 /// <summary>
 /// Creates a new budget
 /// </summary>
 /// <param name="id">Budget id</param>
 /// <param name="name">Budget name</param>
 /// <param name="currencyCode">Currency code</param>
 /// <param name="unitOfWork">Current unit of work</param>
 /// <returns>A new budget</returns>
 public static Budget Create(BudgetId id, string name, string currencyCode, IUnitOfWork unitOfWork)
 {
     return(new Budget(id, name, currencyCode, unitOfWork));
 }
예제 #27
0
 /// <summary>
 /// Load budget from (event) history
 /// </summary>
 /// <param name="id">Budget id</param>
 /// <param name="unitOfWork">Current unit of work</param>
 /// <returns>An existing account, loaded from the event history</returns>
 public static Budget Load(BudgetId id, IUnitOfWork unitOfWork)
 {
     return(new Budget(id, unitOfWork));
 }