Beispiel #1
0
        public async Task <IActionResult> OnGetLoadDetailsPartialAsync(Guid?id)
        {
            if (!id.HasValue)
            {
                return(NotFound());
            }

            var budgetFromRepo = await _context.Budgets
                                 .Include(b => b.Bills)
                                 .ThenInclude(e => e.BudgetCategory)
                                 .FirstOrDefaultAsync(b => b.Id == id.Value);

            if (budgetFromRepo == null)
            {
                return(NotFound());
            }

            Budget = Mapper.Map <BudgetDto>(budgetFromRepo);

            return(new PartialViewResult
            {
                ViewName = "_DetailsPartial",
                ViewData = new ViewDataDictionary <BudgetDto>(ViewData, Budget)
            });
        }
Beispiel #2
0
 public void Create(BudgetDto budget)
 {
     _db.Budgets.Add(new Budget
     {
         Name = budget.Name
     });
 }
        public void Should_Map_BudgetDto_to_Budget()
        {
            // Arrange
            var _mBudget = new Mock <Budget>();

            var budgetDto = new BudgetDto
            {
                IsActive      = true,
                ActualTotal   = 100,
                ForecastTotal = 120,
                StartDate     = _testDateTime,
                EndDate       = _testDateTime,
                SiteId        = 1,
                SubSiteId     = null
            };

            // Act
            CommonHelperAppService.MapDtoToEntityForUpdating(budgetDto, _mBudget.Object);

            // Assert
            Assert.AreEqual(budgetDto.IsActive, _mBudget.Object.IsActive);
            Assert.AreEqual(budgetDto.ActualTotal, _mBudget.Object.ActualTotal);
            Assert.AreEqual(budgetDto.ForecastTotal, _mBudget.Object.ForecastTotal);
            Assert.AreEqual(budgetDto.StartDate, _mBudget.Object.StartDate);
            Assert.AreEqual(budgetDto.EndDate, _mBudget.Object.EndDate);
            Assert.AreEqual(budgetDto.SiteId, _mBudget.Object.SiteId);
            Assert.AreEqual(budgetDto.SubSiteId, _mBudget.Object.SubSiteId);
        }
        public IActionResult Add([FromBody] BudgetDto model)
        {
            try
            {
                if (model == null || !ModelState.IsValid)
                {
                    return(BadRequest("Invalid State"));
                }

                var result = _budgetService.Add(
                    model.Month,
                    model.Year,
                    model.Name,
                    model.Amount,
                    model.Notes
                    );

                if (result == null)
                {
                    return(BadRequest("Invalid budget data"));
                }

                return(Ok(new BudgetDto(result)));
            }
            catch (Exception)
            {
                return(BadRequest("Error while adding budget"));
            }
        }
        public void FailValidation_When_DateIsEmpty()
        {
            var budget    = new BudgetDto();
            var validator = new BudgetDtoValidator();

            var result = validator.TestValidate(budget);

            result.ShouldHaveValidationErrorFor(x => x.Month);
        }
Beispiel #6
0
        public BudgetDto GetBudgetById(int budgetId)
        {
            var       budget    = _budgetServiceParams.BudgetRepository.GetBudgetById(budgetId);
            BudgetDto budgetDto = new BudgetDto();

            budgetDto.Name = budget.Name;

            return(budgetDto);
        }
Beispiel #7
0
        public Spreadsheet GetSpreadsheet(BudgetDto budget)
        {
            _budget = budget;
            SetDefaults();
            AddSpendingSheet();
            AddDashboardSheet();
            AddChartsSheet();

            return(_spreadsheet);
        }
        /// <summary>
        ///  Create a new domain object
        /// </summary>
        /// <param name="value"></param>
        /// <returns>A budget of data.</returns>
        public IBudgetData GetNewDo(string value)
        {
            var newDto = new BudgetDto();

            newDto.NUMERO_PRE = value;
            newDto.IsNew      = true;
            var domainObject = new Budget(newDto);

            return(domainObject);
        }
Beispiel #9
0
 public static void MapDtoToEntityForUpdating(BudgetDto budgetDto, Budget budget)
 {
     budget.IsActive      = budgetDto.IsActive;
     budget.StartDate     = budgetDto.StartDate;
     budget.EndDate       = budgetDto.EndDate;
     budget.ForecastTotal = budgetDto.ForecastTotal;
     budget.ActualTotal   = budgetDto.ActualTotal;
     budget.SiteId        = budgetDto.SiteId;
     budget.SubSiteId     = budgetDto.SubSiteId;
 }
Beispiel #10
0
        public DashboardSheetService(BudgetDto budget)
        {
            _budget = budget ?? throw new ArgumentNullException(nameof(budget));

            int rowsNumber = 3 + (_budget.Categories.Count * 2) + _budget.Subcategories.Count;
            int colsNumber = 4;

            _googleSheetService = new GoogleSheetService("Dashboard", 0, rowsNumber, colsNumber, 0, 2, true, GetSheetsColor());
            _subcategoryRows    = new List <Model.DTOs.GoogleSpreadsheet.DashboardSubcategoryRowDto>();
            _googleSheetService.SetRowHeight(0, 50);
            _googleSheetService.AddProtectedRanges(0, 4, 1, rowsNumber);
        }
        public async Task <IActionResult> CreateBudgetAsync(BudgetDto budget)
        {
            // Create the DB Model form of the budget
            Budget newBudget = Mapper.Map <Budget>(budget);

            // Add and save the changes
            await DbContext.Budgets.AddAsync(newBudget);

            await DbContext.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetBudgetByIdAsync), new { id = newBudget.Id }, newBudget));
        }
        public ChartsSheetService(BudgetDto budget, ILogger log)
        {
            _budget = budget ?? throw new ArgumentNullException(nameof(budget));
            _log    = log;

            int rowsNumber = 5 + _budget.Categories.Count + 54;
            int colsNumber = 7;

            _googleSheetService = new GoogleSheetService("Charts", 2, rowsNumber, colsNumber, 0, 0, true, GetSheetsColor());
            _googleSheetService.SetRowHeight(0, 50);
            _googleSheetService.AddProtectedRanges(0, 2, 1, 3 + _budget.Categories.Count);
        }
Beispiel #13
0
        public async Task <IActionResult> GetSummary()
        {
            var user = await _userService.GetById(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)));

            var budget = new BudgetDto
            {
                Incomes  = await _incomeService.GetAll(user.PlannerId),
                Expenses = await _expenseService.GetAll(user.PlannerId)
            };

            return(Ok(budget));
        }
Beispiel #14
0
        // CRUD
        public void Create(BudgetDto budgetDto, long userId)
        {
            var budget = Mapper.Map <Budget>(budgetDto);

            _unitOfWork.BudgetRepository.Create(budget);
            _unitOfWork.Save();

            // Audit
            _auditLogAppService.Audit(
                AppConstants.ActionTypeCreate,
                AppConstants.BudgetTableName,
                userId,
                budget.Id);
        }
Beispiel #15
0
        public HttpStatusCode PostBudget([FromBody] BudgetDto addBudgetRequest)
        {
            try
            {
                //  Budget budget = _budgetAppService.ParseAddBudgetRequestToBudget(addBudgetRequest);

                //_budgetAppService.CreateNewBudget(budget);
                return(HttpStatusCode.OK);
            }
            catch (Exception exc)
            {
                return(HttpStatusCode.InternalServerError);
            }
        }
        public override async Task Invoke(CancellationToken token)
        {
            var accountRepository = GetRepository <Account>();
            var account           = await accountRepository.FirstOrDefaultAsync(a => a.Id == Command.AccountId && !a.IsDeleted, token)
                                    ?? throw new ArgumentException($"Can't found account by {Command.AccountId}");

            var category = await GetRepository <Category>().FirstOrDefaultAsync(c => c.Id == Command.CategoryId && !c.IsDeleted, token)
                           ?? throw new ArgumentException($"Can't found category by {Command.CategoryId}");

            var snapshot = new OperationSnapshot
            {
                CategoryType = category.Type
            };

            var operation = new BudgetOperation
            {
                Amount        = Command.Amount,
                Type          = OperationType.Budget,
                Comment       = Command.Comment,
                AccountId     = Command.AccountId,
                CategoryId    = Command.CategoryId,
                CreatedOn     = Command.CreatedOn,
                Snapshot      = JsonConvert.SerializeObject(snapshot),
                OperationDate = Command.OperationDate,
                CreatedBy     = Command.CreatedBy
            };

            account.ChangeBalance(category.Type == CategoryType.Income ? operation.Amount : -operation.Amount);

            accountRepository.Update(account);

            var result = await GetRepository <BudgetOperation>().AddAsync(operation, token);

            await SaveAsync();

            var entity = result.Entity;

            Result = new BudgetDto
            {
                Id         = entity.Id,
                Amount     = entity.Amount,
                Comment    = entity.Comment,
                Date       = entity.OperationDate,
                Type       = entity.Type,
                AccountId  = entity.AccountId,
                CategoryId = entity.CategoryId
            };
        }
        public SpendingSheetService(BudgetDto budget)
        {
            _budget = budget;
            int rowsNumber = 16 + (_budget.Incomes.Count + 4) + (_budget.Categories.Count * 4) + _budget.Subcategories.Count;
            int colsNumber = 6 + DateTime.DaysInMonth(_budget.Month.Year, _budget.Month.Month);

            _googleSheetService       = new GoogleSheetService("Spending", 1, rowsNumber, colsNumber, 5, 0, false, GetSheetsColor());
            _subcategoriesRowsIndexes = new List <int>();
            _subcategoriesRows        = new List <CellData>();
            _googleSheetService.SetRowHeight(0, 50);
            _googleSheetService.SetColumnWidth(0, 180);
            _googleSheetService.SetColumnWidth(1, 110);
            _googleSheetService.SetColumnWidth(2, 110);
            _googleSheetService.SetColumnWidth(3, 110);
            _googleSheetService.SetColumnWidth(4, 100);
        }
Beispiel #18
0
        public void Update(BudgetDto budgetDto, long userId)
        {
            var budget = _unitOfWork.BudgetRepository.GetById(budgetDto.Id);

            CommonHelperAppService.MapDtoToEntityForUpdating(budgetDto, budget);

            _unitOfWork.BudgetRepository.Update(budget);
            _unitOfWork.Save();

            // Audit
            _auditLogAppService.Audit(
                AppConstants.ActionTypeUpdate,
                AppConstants.BudgetTableName,
                userId,
                budget.Id);
        }
        public async Task <IActionResult> UpdateBudgetAsync(BudgetDto budget)
        {
            // Get the budget using the supplied id
            var existingBudget = await DbContext.Budgets.FirstOrDefaultAsync(b => b.Id == budget.Id);

            if (existingBudget == null)
            {
                return(NotFound());
            }

            // Update the DB model
            Mapper.Map(budget, existingBudget);
            DbContext.SaveChanges();

            return(Ok());
        }
Beispiel #20
0
        public GetBudgetFixture()
        {
            RepoMock   = new Mock <IBudgetRepository>();
            MapperMock = new Mock <IMapper>();
            AuthenticationProviderMock = new Mock <IAuthenticationProvider>();

            RepositoryResult = new Domain.Entities.Budget()
            {
                Id           = It.IsAny <int>(),
                Name         = It.IsAny <string>(),
                CurrencyCode = It.IsAny <eCurrency>(),
                StartingDate = It.IsAny <DateTime>()
            };

            MapperResult = new BudgetDto()
            {
                BudgetId     = It.IsAny <int>(),
                Name         = It.IsAny <string>(),
                Currency     = It.IsAny <Currency>(),
                StartingDate = It.IsAny <DateTime>()
            };

            var mockUser    = new Mock <User>();
            var mockUserDto = new Mock <UserDto>();

            RepoMock.Setup(x => x.GetByIdAsync(It.IsInRange(int.MinValue, 0, Range.Inclusive)))
            .ReturnsAsync(default(Domain.Entities.Budget));

            RepoMock.Setup(x => x.GetByIdAsync(It.IsInRange(1, int.MaxValue, Range.Inclusive)))
            .ReturnsAsync(RepositoryResult);

            MapperMock.Setup(m => m.Map <BudgetDto>(It.IsAny <Domain.Entities.Budget>()))
            .Returns(MapperResult);

            AuthenticationProviderMock.Setup(m => m.User).Returns(mockUserDto.Object);
            AuthenticationProviderMock.Setup(m => m.IsAuthenticated).Returns(true);

            RequestHandler  = new GetBudget.Handler(RepoMock.Object, MapperMock.Object, AuthenticationProviderMock.Object);
            RequestResponse = RequestHandler.Handle(new GetBudget.Query()
            {
                BudgetId = 1
            }, new CancellationToken());
            IncorrectRequestResponse = RequestHandler.Handle(new GetBudget.Query()
            {
                BudgetId = 1
            }, new CancellationToken());
        }
        public async Task <Budget> NewBudgetAsync(BudgetRequest budgetRequest, string userId)
        {
            var budgetDto = new BudgetDto
            {
                CreatedAt   = DateTime.UtcNow,
                UpdatedAt   = DateTime.UtcNow,
                Name        = budgetRequest.Name,
                Description = budgetRequest.Description,
                UserId      = userId
            };

            var budget = _mapper.Map <Budget>(budgetDto);

            var created = await _baseRepository.CreateEntityAsync(budget);

            return(created);
        }
Beispiel #22
0
        public async Task AddAsync(BudgetDto dto)
        {
            var typeBudget = (TypeBudget)dto.TypeBudget;

            var user = await _userRepository.GetByNameAsync(dto.Username);

            if (user == null)
            {
                throw new Exception("User don't exist");
            }

            var budget = new Budget(dto.Description, dto.Value, dto.DateTime, typeBudget, user);

            user.AddNewBudget(budget);

            _repository.AddAsync(budget);
            _userRepository.UpdateAsync(user);
        }
Beispiel #23
0
        public async Task <IActionResult> OnGetDeletePartialAsync(Guid?id)
        {
            if (id.HasValue)
            {
                var budgetFromRepo = await _context.Budgets.FindAsync(id);

                Budget = Mapper.Map <BudgetDto>(budgetFromRepo);

                if (Budget != null)
                {
                    return(new PartialViewResult
                    {
                        ViewName = "_DeletePartial",
                        ViewData = new ViewDataDictionary <BudgetDto>(ViewData, Budget)
                    });
                }
            }

            return(RedirectToPage("./Index"));
        }
        public IActionResult Update([FromBody] BudgetDto model)
        {
            try
            {
                if (model == null || !ModelState.IsValid)
                {
                    return(BadRequest("Invalid State"));
                }

                var success = _budgetService.Update(model.Id, model.Month, model.Year, model.Name, model.Amount, model.Notes);

                return(Ok(new UpdateResultDto
                {
                    Success = success,
                    Error = success ? "" : "Invalid budget information"
                }));
            }
            catch (Exception)
            {
                return(BadRequest("Error while updating"));
            }
        }
Beispiel #25
0
        private void CleanUpTheData(BudgetDto budget)
        {
            _budget.Categories = _budget.Categories.Where(x => String.IsNullOrEmpty(x.Name) == false).ToList();

            foreach (var subcategory in _budget.Subcategories.Where(x => String.IsNullOrEmpty(x.Name) == false))
            {
                if (subcategory.Amount == null)
                {
                    subcategory.Amount = 0;
                }
            }

            foreach (var income in _budget.Incomes.Where(x => String.IsNullOrEmpty(x.Name) == false))
            {
                if (income.Amount == null)
                {
                    income.Amount = 0;
                }
            }

            Guid[] categoriesIds = _budget.Subcategories.GroupBy(x => x.CategoryId).Select(x => x.Key).ToArray();
            _budget.Categories = _budget.Categories.Where(x => categoriesIds.Contains(x.Id)).ToList();
        }
Beispiel #26
0
        public async Task <IActionResult> Generate([FromBody] BudgetDto input)
        {
            _budget = input;

            if (_jwtToken.UserId == null)
            {
                return(new UnauthorizedResult());
            }

            _log.LogInformation($"Budget: {JsonConvert.SerializeObject(_budget)}");

            var auth0User = await _userManagementService.GetAuth0UserAsync(_jwtToken.UserId);

            if (_budget.User.AgreedToNewsletter)
            {
                if (!string.IsNullOrEmpty(auth0User.Email))
                {
                    await _subscriberService.HandleMemberSubscriptionAsync(new NewSubscriberDto()
                    {
                        Email  = auth0User.Email,
                        Name   = auth0User?.GivenName ?? "",
                        Source = "MVP-Generator",
                    });
                }
            }

            await SaveBudgetAsync(_jwtToken.UserId);

            _log.LogInformation($"Auth0User: {JsonConvert.SerializeObject(auth0User)}");

            CleanUpTheData(_budget);
            var    googleSpreadsheet = GetRequestJsonForGoogle();
            string googleRespone     = await CreateSpreadsheet(auth0User, googleSpreadsheet);

            return(Ok(googleRespone));
        }
Beispiel #27
0
        public async Task <IActionResult> PostAsync(BudgetDto dto)
        {
            await _service.AddAsync(dto);

            return(Created("", dto));
        }
Beispiel #28
0
 public Query(BudgetDto budget)
 {
     Budget = budget;
 }
 public async Task CreateOrUpdateBudgetAsync(BudgetDto input)
 {
     await _budgetManager.CreateOrUpdateBudgetAsync(input.MapTo <Budget>());
 }
Beispiel #30
0
 /// <summary>
 ///  Budget
 /// </summary>
 /// <param name="value"></param>
 public Budget(BudgetDto value)
 {
     _dto  = value;
     Code  = value.NUMERO_PRE;
     Valid = true;
 }