public ActionResult Details(int id = 0)
        {
            if (Authorized(RoleType.SystemManager))
            {
                Budget budget;
                using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
                {
                    budget = budgetsRep.GetEntity(id, "Company");
                }

                if (budget != null)
                {
                    if (budget.CompanyId == CurrentUser.CompanyId)
                    {
                        return(View(budget));
                    }
                    else
                    {
                        return(Error(Loc.Dic.error_no_permission));
                    }
                }
                else
                {
                    return(Error(Loc.Dic.error_budgets_get_error));
                }
            }
            else
            {
                return(Error(Loc.Dic.error_no_permission));
            }
        }
Exemple #2
0
            public void UpdatesBudgetInTheContext()
            {
                // Act.
                using (CheckbookContext context = new CheckbookContext(this.dbContextOptions))
                {
                    BudgetsRepository repository = new BudgetsRepository(context);
                    repository.Save(this.budget, this.userId);
                }

                // Assert.
                using (CheckbookContext context = new CheckbookContext(this.dbContextOptions))
                {
                    int expectedBudgetCount = 5;
                    Assert.AreEqual(expectedBudgetCount, context.Budgets.Count(), "The number of budgets should not change.");

                    Budget actual = ContextDataService.GetBudgetsSet(context)
                                    .FirstOrDefault(x => x.Id == this.budget.Id);
                    Assert.IsNotNull(actual, "A budget should be found.");

                    Budget expected = this.budget;
                    Assert.AreEqual(expected.Id, actual.Id, "The ID for the entity should match.");
                    Assert.AreEqual(expected.Name, actual.Name, "The name for the entity should match.");
                    Assert.AreEqual(expected.UserId, actual.UserId, "The user ID for the entity should match.");
                }
            }
Exemple #3
0
            public void ThrowsExceptionWhenBudgetWithMismatchedUserIds()
            {
                // Arrange.
                this.budget.UserId = 1;
                this.userId        = 2;

                // Act.
                Exception caughtException = null;

                try
                {
                    using (CheckbookContext context = new CheckbookContext(this.dbContextOptions))
                    {
                        BudgetsRepository repository = new BudgetsRepository(context);
                        repository.Save(this.budget, this.userId);
                    }
                }
                catch (Exception ex)
                {
                    caughtException = ex;
                }

                // Assert.
                Assert.IsNotNull(caughtException, "An exception should be thrown.");
                Assert.IsInstanceOfType(caughtException, typeof(ArgumentException), "This should be an argument exception.");
                string exceptionMessage = "A user ID is expected to match the passed in user ID for a budget.\r\nParameter name: budget.UserId";

                Assert.AreEqual(exceptionMessage, caughtException.Message, "The exception message should be correct.");
            }
Exemple #4
0
            public void ThrowsExceptionWhenIdZero()
            {
                // Arrange.
                this.budget.Id = 0;

                // Act.
                Exception caughtException = null;

                try
                {
                    using (CheckbookContext context = new CheckbookContext(this.dbContextOptions))
                    {
                        BudgetsRepository repository = new BudgetsRepository(context);
                        repository.Save(this.budget, this.userId);
                    }
                }
                catch (Exception ex)
                {
                    caughtException = ex;
                }

                // Assert.
                Assert.IsNotNull(caughtException, "An exception should be thrown.");
                Assert.IsInstanceOfType(caughtException, typeof(ArgumentException), "This should be an argument exception.");
                string exceptionMessage = "A budget with a specified ID should have been used. To add a budget, use the Add method.\r\nParameter name: budget.Id";

                Assert.AreEqual(exceptionMessage, caughtException.Message, "The exception message should be correct.");
            }
        public ActionResult Import(HttpPostedFileBase file, int?id, string name, int?year, string budgetType)
        {
            if (!Authorized(RoleType.SystemManager))
            {
                return(Error(Loc.Dic.error_no_permission));
            }
            if (file != null && file.ContentLength <= 0)
            {
                return(Error(Loc.Dic.error_invalid_form));
            }
            if (string.IsNullOrEmpty(budgetType))
            {
                return(Error(Loc.Dic.Error_chooseMonthelyOrYearlyBudget));
            }
            if (!(budgetType == "Month" || budgetType == "Year"))
            {
                return(Error(Loc.Dic.Error_no_budgetType));
            }


            if (id.HasValue)
            {
                string moved = Interfaces.ImportBudget(file.InputStream, CurrentUser.CompanyId, id.Value, budgetType);
                if (moved == "OK")
                {
                    return(RedirectToAction("index"));
                }
                else
                {
                    return(Error(moved));
                }
            }
            else if (year.HasValue)
            {
                if (year.Value > DateTime.Now.Year + 10 || year.Value < DateTime.Now.Year - 1)
                {
                    return(Error(Loc.Dic.error_invalid_budget_year));
                }

                using (BudgetsRepository budgetsRepository = new BudgetsRepository(CurrentUser.CompanyId))
                {
                    Budget newBudget = new Budget();
                    newBudget.Name      = name;
                    newBudget.Year      = year.Value;
                    newBudget.CompanyId = CurrentUser.CompanyId;
                    newBudget.IsActive  = false;
                    budgetsRepository.Create(newBudget);
                    string moved = Interfaces.ImportBudget(file.InputStream, CurrentUser.CompanyId, newBudget.Id, budgetType);
                    if (moved == "OK")
                    {
                        return(RedirectToAction("index"));
                    }
                    else
                    {
                        return(Error(moved));
                    }
                }
            }
            return(Error(Loc.Dic.error_invalid_form));
        }
        public ActionResult Index()
        {
            if (Authorized(RoleType.SystemManager))
            {
                List <Budgets_Allocations> model;
                List <SelectListItemDB>    budgetsList;

                using (BudgetsRepository budgetRep = new BudgetsRepository(CurrentUser.CompanyId))
                    using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                    {
                        model = allocationsRep.GetList("Budgets_Expenses", "Budgets_Incomes").Where(x => x.CompanyId == CurrentUser.CompanyId).ToList();

                        budgetsList = budgetRep.GetList()
                                      .Where(budget => budget.CompanyId == CurrentUser.CompanyId && budget.Year >= (DateTime.Now.Year - 1))
                                      .Select(a => new { Id = a.Id, Name = a.Year })
                                      .AsEnumerable()
                                      .Select(x => new SelectListItemDB()
                        {
                            Id = x.Id, Name = x.Name.ToString()
                        })
                                      .ToList();
                    }

                ViewBag.BudgetId = new SelectList(budgetsList, "Id", "Name");
                return(View(model));
            }
            else
            {
                return(Error(Loc.Dic.error_no_permission));
            }
        }
Exemple #7
0
            public void ReturnsBudgetsOnlyForTheUser()
            {
                // Act.
                List <BudgetSummary> actualList;

                using (CheckbookContext context = new CheckbookContext(this.dbContextOptions))
                {
                    BudgetsRepository repository = new BudgetsRepository(context);
                    actualList = repository.GetTotals(this.userId).ToList();
                }

                // Assert.
                using (CheckbookContext context = new CheckbookContext(this.dbContextOptions))
                {
                    int numberOfBudgetUsers = context.Budgets
                                              .GroupBy(a => a.UserId)
                                              .Count();
                    Assert.AreNotEqual(numberOfBudgetUsers, 0, "For the test to work there must be more than one user with budgets.");
                    Assert.AreNotEqual(numberOfBudgetUsers, 1, "For the test to work there must be more than one user with budgets.");
                }

                foreach (BudgetSummary actual in actualList)
                {
                    Assert.AreEqual(this.userId, actual.UserId, "The user ID for each budget should match the input user ID.");
                }
            }
Exemple #8
0
            public void ThrowsExceptionWhenRecordFoundDoesNotBelongToTheUser()
            {
                // Arrange.
                this.budgetId = 1;
                this.userId   = 2;

                // Act.
                Exception caughtException = null;

                try
                {
                    using (CheckbookContext context = new CheckbookContext(this.dbContextOptions))
                    {
                        BudgetsRepository repository = new BudgetsRepository(context);
                        repository.Get(this.budgetId, this.userId);
                    }
                }
                catch (Exception ex)
                {
                    caughtException = ex;
                }

                // Assert.
                Assert.IsNotNull(caughtException, "An exception should be thrown.");
                Assert.IsInstanceOfType(caughtException, typeof(NotFoundException), "This should be an argument exception.");
                string exceptionMessage = "The budget was not found.";

                Assert.AreEqual(exceptionMessage, caughtException.Message, "The exception message should be correct.");
            }
        public ActionResult Edit(int id = 0)
        {
            return(Error(Loc.Dic.error_no_permission));

            if (Authorized(RoleType.SystemManager))
            {
                Budgets_Allocations     allocation;
                List <SelectListItemDB> incomesList;
                List <SelectListItemDB> expensesList;

                using (AllocationRepository allocationRep = new AllocationRepository(CurrentUser.CompanyId))
                    using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
                        using (BudgetsIncomesRepository incomesRep = new BudgetsIncomesRepository())
                            using (BudgetsExpensesRepository expensesRep = new BudgetsExpensesRepository())
                            {
                                allocation = allocationRep.GetEntity(id);

                                if (allocation != null)
                                {
                                    if (allocation.CompanyId == CurrentUser.CompanyId)
                                    {
                                        incomesList = incomesRep.GetList()
                                                      .Where(income => income.CompanyId == CurrentUser.CompanyId && income.BudgetId == allocation.BudgetId)
                                                      .Select(x => new SelectListItemDB()
                                        {
                                            Id = x.Id, Name = x.CustomName
                                        })
                                                      .ToList();

                                        expensesList = expensesRep.GetList()
                                                       .Where(expense => expense.CompanyId == CurrentUser.CompanyId && expense.BudgetId == allocation.BudgetId)
                                                       .Select(x => new SelectListItemDB()
                                        {
                                            Id = x.Id, Name = x.CustomName
                                        })
                                                       .ToList();

                                        ViewBag.IncomeId  = new SelectList(incomesList, "Id", "Name", allocation.IncomeId);
                                        ViewBag.ExpenseId = new SelectList(expensesList, "Id", "Name", allocation.ExpenseId);

                                        return(View(allocation));
                                    }
                                    else
                                    {
                                        return(Error(Loc.Dic.error_no_permission));
                                    }
                                }
                                else
                                {
                                    return(Error(Loc.Dic.error_database_error));
                                }
                            }
            }
            else
            {
                return(Error(Loc.Dic.error_no_permission));
            }
        }
        public ActionResult EditAllocations(int id = 0, int budgetId = 0)
        {
            if (!Authorized(RoleType.SystemManager))
            {
                return(Error(Loc.Dic.error_no_permission));
            }

            PermissionAllocationsModel model = new PermissionAllocationsModel();
            Budget budget;

            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
                using (BudgetsPermissionsRepository permissionsRep = new BudgetsPermissionsRepository())
                    using (BasketsToAllocationsRepository permissionsAllocationsRep = new BasketsToAllocationsRepository())
                    {
                        model.Basket = permissionsRep.GetEntity(id);

                        if (model.Basket == null)
                        {
                            return(Error(Loc.Dic.error_permissions_get_error));
                        }

                        if (model.Basket.CompanyId != CurrentUser.CompanyId)
                        {
                            return(Error(Loc.Dic.error_no_permission));
                        }

                        budget = budgetsRep.GetEntity(budgetId);

                        if (budget == null)
                        {
                            return(Error(Loc.Dic.error_database_error));
                        }

                        List <PermissionAllocation> permissionsToAllocations = permissionsAllocationsRep.GetList("Budgets_Allocations", "Budgets_Allocations.Budgets_Incomes", "Budgets_Allocations.Budgets_Expenses")
                                                                               .Where(x => x.BudgetId == budget.Id && x.BasketId == model.Basket.Id)
                                                                               .AsEnumerable()
                                                                               .Select(alloc => new PermissionAllocation()
                        {
                            IsActive = true, Allocation = alloc
                        })
                                                                               .ToList();

                        model.BudgetAllocations = new BudgetAllocations()
                        {
                            Budget                = budget,
                            AllocationsList       = budget.Budgets_Allocations.OrderBy(x => x.SortingCode).ToList(),
                            PermissionAllocations = permissionsToAllocations
                        };

                        return(View(model));
                    }
        }
        public ActionResult Create(int id = 0)
        {
            return Error(Loc.Dic.error_no_permission);
            if (Authorized(RoleType.SystemManager))
            {
                Budget budget;
                List<SelectListItemDB> incomesList;
                List<SelectListItemDB> expensesList;

                using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
                using (BudgetsIncomesRepository incomesRep = new BudgetsIncomesRepository())
                using (BudgetsExpensesRepository expensesRep = new BudgetsExpensesRepository())
                {
                    budget = budgetsRep.GetEntity(id);

                    if (budget != null)
                    {
                        if (budget.CompanyId == CurrentUser.CompanyId)
                        {
                            incomesList = incomesRep.GetList()
                                .Where(income => income.CompanyId == CurrentUser.CompanyId && income.BudgetId == budget.Id)
                                .Select(x => new SelectListItemDB() { Id = x.Id, Name = x.CustomName })
                                .ToList();

                            expensesList = expensesRep.GetList()
                                .Where(expense => expense.CompanyId == CurrentUser.CompanyId && expense.BudgetId == budget.Id)
                                .Select(x => new SelectListItemDB() { Id = x.Id, Name = x.CustomName })
                                .ToList();

                            ViewBag.BudgetId = id;
                            ViewBag.IncomeId = new SelectList(incomesList, "Id", "Name");
                            ViewBag.ExpenseId = new SelectList(expensesList, "Id", "Name");

                            return View();
                        }
                        else
                        {
                            return Error(Loc.Dic.error_no_permission);
                        }
                    }
                    else
                    {
                        return Error(Loc.Dic.error_database_error);
                    }
                }
            }
            else
            {
                return Error(Loc.Dic.error_no_permission);
            }
        }
Exemple #12
0
            public void ReturnsBudgetFromContext()
            {
                // Act.
                Budget actual;

                using (CheckbookContext context = new CheckbookContext(this.dbContextOptions))
                {
                    BudgetsRepository repository = new BudgetsRepository(context);
                    actual = repository.Save(this.budget, this.userId);
                }

                // Assert.
                Assert.AreEqual(this.budget.Id, actual.Id, "The ID for the entity should match.");
            }
Exemple #13
0
        public ActionResult Create()
        {
            return(Error(Loc.Dic.Error_NoPermission));

            if (Authorized(RoleType.SystemManager))
            {
                using (BudgetsRepository budgetRep = new BudgetsRepository(CurrentUser.CompanyId))
                    using (BudgetsExpensesRepository expensesRep = new BudgetsExpensesRepository())
                        using (ParentProjectsRepository projectsRep = new ParentProjectsRepository())
                            using (SubProjectsRepository subProjectsRep = new SubProjectsRepository())
                            {
                                List <SelectListItemDB> budgetsList = budgetRep.GetList()
                                                                      .Where(budget => budget.CompanyId == CurrentUser.CompanyId && budget.Year >= (DateTime.Now.Year - 1))
                                                                      .Select(a => new { Id = a.Id, Name = a.Year })
                                                                      .AsEnumerable()
                                                                      .Select(x => new SelectListItemDB()
                                {
                                    Id = x.Id, Name = x.Name.ToString()
                                })
                                                                      .ToList();

                                List <SelectListItemDB> projectsList = projectsRep.GetList()
                                                                       .Where(project => project.CompanyId == CurrentUser.CompanyId && project.IsActive)
                                                                       .Select(x => new SelectListItemDB()
                                {
                                    Id = x.Id, Name = x.Name
                                })
                                                                       .ToList();

                                List <SelectListItemDB> subProjectsList = subProjectsRep.GetList()
                                                                          .Where(subProject => subProject.CompanyId == CurrentUser.CompanyId && subProject.IsActive)
                                                                          .Select(x => new SelectListItemDB()
                                {
                                    Id = x.Id, Name = x.Name
                                })
                                                                          .ToList();

                                ViewBag.BudgetId        = new SelectList(budgetsList, "Id", "Name");
                                ViewBag.ParentProjectId = new SelectList(projectsList, "Id", "Name");
                                ViewBag.SubProjectId    = new SelectList(subProjectsList, "Id", "Name");
                            }

                return(View());
            }
            else
            {
                return(Error(Loc.Dic.error_no_permission));
            }
        }
        public ActionResult Create()
        {
            return(Error(Loc.Dic.Error_NoPermission));

            if (Authorized(RoleType.SystemManager))
            {
                using (BudgetsRepository budgetRep = new BudgetsRepository(CurrentUser.CompanyId))
                    using (BudgetsIncomesRepository incomesRep = new BudgetsIncomesRepository())
                        using (IncomeTypesRepository incomeTypesRep = new IncomeTypesRepository())
                            using (InstitutionsRepository institutionsRep = new InstitutionsRepository())
                            {
                                List <SelectListItemDB> budgetsList = budgetRep.GetList()
                                                                      .Where(budget => budget.CompanyId == CurrentUser.CompanyId && budget.Year >= (DateTime.Now.Year - 1))
                                                                      .Select(a => new { Id = a.Id, Name = a.Year })
                                                                      .AsEnumerable()
                                                                      .Select(x => new SelectListItemDB()
                                {
                                    Id = x.Id, Name = x.Name.ToString()
                                })
                                                                      .ToList();

                                List <SelectListItemDB> incomeTypesList = incomeTypesRep.GetList()
                                                                          .Select(x => new SelectListItemDB()
                                {
                                    Id = x.Id, Name = x.Name
                                })
                                                                          .ToList();

                                List <SelectListItemDB> institutionsList = institutionsRep.GetList()
                                                                           .Where(type => type.CompanyId == CurrentUser.CompanyId)
                                                                           .Select(x => new SelectListItemDB()
                                {
                                    Id = x.Id, Name = x.Name
                                })
                                                                           .ToList();

                                ViewBag.BudgetId                  = new SelectList(budgetsList, "Id", "Name");
                                ViewBag.BudgetIncomeTypeId        = new SelectList(incomeTypesList, "Id", "Name");
                                ViewBag.BudgetsIncomeInstitutions = new SelectList(institutionsList, "Id", "Name");
                            }

                return(View());
            }
            else
            {
                return(Error(Loc.Dic.error_no_permission));
            }
        }
        public ActionResult Create(Budget budget)
        {
            if (Authorized(RoleType.SystemManager))
            {
                if (ModelState.IsValid)
                {
                    if (budget.Year >= DateTime.Now.Year)
                    {
                        budget.CompanyId = CurrentUser.CompanyId;
                        budget.IsActive  = false;

                        bool wasCreated;
                        using (BudgetsRepository budgetRep = new BudgetsRepository(CurrentUser.CompanyId))
                        {
                            bool yearExists = budgetRep.GetList().Any(x => x.CompanyId == CurrentUser.CompanyId && x.Year == budget.Year);

                            if (yearExists)
                            {
                                return(Error(Loc.Dic.error_budgets_year_exists));
                            }

                            wasCreated = budgetRep.Create(budget);
                        }

                        if (wasCreated)
                        {
                            return(RedirectToAction("Index"));
                        }
                        else
                        {
                            return(Error(Loc.Dic.error_budgets_create_error));
                        }
                    }
                    else
                    {
                        return(Error(Loc.Dic.error_budgets_year_passed));
                    }
                }
                else
                {
                    return(Error(ModelState));
                }
            }
            else
            {
                return(Error(Loc.Dic.error_no_permission));
            }
        }
        public ActionResult Export(int id = 0)
        {
            if (Authorized(RoleType.SystemManager))
            {
                Budget budgetFromDb;
                List <Budgets_Allocations> allocations = new List <Budgets_Allocations>();

                using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
                {
                    budgetFromDb = budgetsRep.GetEntity(id, "Budgets_Allocations.Budgets_AllocationToMonth");

                    if (budgetFromDb != null)
                    {
                        allocations = budgetFromDb.Budgets_Allocations.ToList();
                    }
                }

                if (allocations != null)
                {
                    StringBuilder builder = new StringBuilder();

                    foreach (var allocation in allocations)
                    {
                        for (int monthNumber = 1; monthNumber <= 12; monthNumber++)
                        {
                            var     allocationMonth = allocation.Budgets_AllocationToMonth.SingleOrDefault(x => x.MonthId == monthNumber);
                            decimal monthAmount     = allocationMonth == null ? 0 : allocationMonth.Amount;

                            builder.Append(String.Format("{0} ", monthAmount));
                        }

                        builder.AppendLine();
                    }

                    return(File(Encoding.UTF8.GetBytes(builder.ToString()),
                                "text/plain",
                                string.Format("{0} - Budget {1}.txt", CurrentUser.CompanyName, budgetFromDb.Year)));
                }
                else
                {
                    return(Error(Loc.Dic.error_database_error));
                }
            }
            else
            {
                return(Error(Loc.Dic.error_no_permission));
            }
        }
        public ActionResult Import(int?id)
        {
            if (!Authorized(RoleType.SystemManager))
            {
                return(Error(Loc.Dic.error_no_permission));
            }
            if (!id.HasValue)
            {
                return(View());
            }

            using (BudgetsRepository budgetsRepository = new BudgetsRepository(CurrentUser.CompanyId))
                ViewBag.Year = budgetsRepository.GetEntity(id.Value).Year;

            return(View(id));
        }
Exemple #18
0
            public void ReturnsEmptyListWhenNoRecordsFound()
            {
                // Arrange.
                this.userId = 123;

                // Act.
                List <BudgetSummary> actualList;

                using (CheckbookContext context = new CheckbookContext(this.dbContextOptions))
                {
                    BudgetsRepository repository = new BudgetsRepository(context);
                    actualList = repository.GetTotals(this.userId).ToList();
                }

                // Assert.
                Assert.AreEqual(0, actualList.Count(), "An empty list should be returned.");
            }
        public ActionResult Index(int page = FIRST_PAGE, string sortby = DEFAULT_SORT, string order = DEFAULT_DESC_ORDER)
        {
            if (!Authorized(RoleType.SystemManager))
            {
                return(Error(Loc.Dic.error_no_permission));
            }

            IEnumerable <Budget> budgets;

            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
            {
                budgets = budgetsRep.GetList().Where(x => x.CompanyId == CurrentUser.CompanyId);

                budgets = Pagination(budgets, page, sortby, order);

                return(View(budgets.ToList()));
            }
        }
        public ActionResult AllocationMontheList(int id = 0, int page = FIRST_PAGE, string sortby = DEFAULT_SORT, string order = DEFAULT_DESC_ORDER)
        {
            if (!Authorized(RoleType.SystemManager))
                return Error(Loc.Dic.error_no_permission);

            IEnumerable<Budgets_Allocations> allocationsList;

            using (BudgetsRepository budgetsRepository = new BudgetsRepository(CurrentUser.CompanyId))
            using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
            {
                allocationsList = allocationsRep.GetList("Budgets_AllocationToMonth").Where(x => x.BudgetId == id);

                allocationsList = Pagination(allocationsList, page, sortby, order);

                ViewBag.BudgetId = id;
                ViewBag.Year = budgetsRepository.GetEntity(id).Year;
                return View(allocationsList.ToList());
            }
        }
        public ActionResult Create(int permissionId, int budgetId)
        {
            Budgets_BasketsToAllocation perAlloc = new Budgets_BasketsToAllocation();
            using (BudgetsRepository budgetsRepository = new BudgetsRepository(CurrentUser.CompanyId))
            using (BudgetsPermissionsRepository permissionsRepository = new BudgetsPermissionsRepository())
            using (AllocationRepository allocationRepository = new AllocationRepository(CurrentUser.CompanyId))
            {
                ViewBag.AllocationList = new SelectList(allocationRepository.GetList().Where(x => x.BudgetId == budgetId).OrderBy(x => x.ExternalId).ToList(), "Id", "DisplayName");
                //ViewBag.BudgetsAllocationId = new SelectList(db.Budgets_Allocations, "Id", "Id");
                perAlloc.BudgetId = budgetId;
                perAlloc.BasketId = permissionId;
                Budget budget = budgetsRepository.GetEntity(budgetId);
                ViewBag.budgetYear = budget.Year;
                Budgets_Baskets permission = permissionsRepository.GetEntity(permissionId);
                ViewBag.PermissionName = permission.Name;

            }
            return View(perAlloc);
        }
        public ActionResult Create(int permissionId, int budgetId)
        {
            Budgets_BasketsToAllocation perAlloc = new Budgets_BasketsToAllocation();

            using (BudgetsRepository budgetsRepository = new BudgetsRepository(CurrentUser.CompanyId))
                using (BudgetsPermissionsRepository permissionsRepository = new BudgetsPermissionsRepository())
                    using (AllocationRepository allocationRepository = new AllocationRepository(CurrentUser.CompanyId))
                    {
                        ViewBag.AllocationList = new SelectList(allocationRepository.GetList().Where(x => x.BudgetId == budgetId).OrderBy(x => x.ExternalId).ToList(), "Id", "DisplayName");
                        //ViewBag.BudgetsAllocationId = new SelectList(db.Budgets_Allocations, "Id", "Id");
                        perAlloc.BudgetId = budgetId;
                        perAlloc.BasketId = permissionId;
                        Budget budget = budgetsRepository.GetEntity(budgetId);
                        ViewBag.budgetYear = budget.Year;
                        Budgets_Baskets permission = permissionsRepository.GetEntity(permissionId);
                        ViewBag.PermissionName = permission.Name;
                    }
            return(View(perAlloc));
        }
        public ActionResult ActivateConfirmed(int id)
        {
            if (Authorized(RoleType.SystemManager))
            {
                Budget budget;
                using (BudgetsRepository budgetRep = new BudgetsRepository(CurrentUser.CompanyId))
                {
                    budget = budgetRep.GetEntity(id);

                    if (budget != null)
                    {
                        if (!budget.IsActive)
                        {
                            Budget oldBudget = budgetRep.GetList().Where(b => b.CompanyId == CurrentUser.CompanyId).SingleOrDefault(x => x.IsActive);

                            if (oldBudget != null)
                            {
                                oldBudget.IsActive = false;
                                budgetRep.Update(oldBudget);
                            }

                            budget.IsActive = true;
                            budgetRep.Update(budget);

                            return RedirectToAction("Index");
                        }
                        else
                        {
                            return Error(Loc.Dic.error_budgets_already_active);
                        }
                    }
                    else
                    {
                        return Error(Loc.Dic.error_budgets_get_error);
                    }
                }
            }
            else
            {
                return Error(Loc.Dic.error_no_permission);
            }
        }
        public ActionResult ActivateConfirmed(int id)
        {
            if (Authorized(RoleType.SystemManager))
            {
                Budget budget;
                using (BudgetsRepository budgetRep = new BudgetsRepository(CurrentUser.CompanyId))
                {
                    budget = budgetRep.GetEntity(id);

                    if (budget != null)
                    {
                        if (!budget.IsActive)
                        {
                            Budget oldBudget = budgetRep.GetList().Where(b => b.CompanyId == CurrentUser.CompanyId).SingleOrDefault(x => x.IsActive);

                            if (oldBudget != null)
                            {
                                oldBudget.IsActive = false;
                                budgetRep.Update(oldBudget);
                            }

                            budget.IsActive = true;
                            budgetRep.Update(budget);

                            return(RedirectToAction("Index"));
                        }
                        else
                        {
                            return(Error(Loc.Dic.error_budgets_already_active));
                        }
                    }
                    else
                    {
                        return(Error(Loc.Dic.error_budgets_get_error));
                    }
                }
            }
            else
            {
                return(Error(Loc.Dic.error_no_permission));
            }
        }
Exemple #25
0
            public void ReturnsBudgetTotalsFromContext()
            {
                // Act.
                List <BudgetSummary> actualList;

                using (CheckbookContext context = new CheckbookContext(this.dbContextOptions))
                {
                    BudgetsRepository repository = new BudgetsRepository(context);
                    actualList = repository.GetTotals(this.userId).ToList();
                }

                // Assert.
                Assert.AreEqual(this.entities.Count(), actualList.Count(), "The entity count should match.");

                BudgetSummary expected = new BudgetSummary(this.entities.ElementAt(0));
                BudgetSummary actual   = actualList.ElementAt(0);
                string        index    = "first";

                Assert.AreNotEqual(0, actual.Balance, "The current total should not be zero.");
                Assert.AreEqual(expected.Balance, actual.Balance, $"The current total for the {index} entity should match.");
            }
        public ActionResult BudgetBaskets(int id = 0, int page = FIRST_PAGE, string sortby = DEFAULT_SORT, string order = DEFAULT_DESC_ORDER)
        {
            if (!Authorized(RoleType.SystemManager)) return Error(Loc.Dic.error_no_permission);

            IEnumerable<Budgets_Baskets> baskets;
            Budgets_BasketsToAllocation per = new Budgets_BasketsToAllocation();

            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
            using (BudgetsPermissionsRepository permissionsRep = new BudgetsPermissionsRepository())
            {
                baskets = permissionsRep.GetList("Budgets_BasketsToAllocation").Where(x => x.CompanyId == CurrentUser.CompanyId);

                baskets = Pagination(baskets, page, sortby, order, true);

                ViewBag.budgetId = id;
                Budget budget = budgetsRep.GetList().SingleOrDefault(x => x.Id == id);
                ViewBag.budgetYear = budget.Year;
                ViewBag.budgetId = budget.Id;
                return View(baskets.ToList());
            }
        }
        public ActionResult AllocationMontheList(int id = 0, int page = FIRST_PAGE, string sortby = DEFAULT_SORT, string order = DEFAULT_DESC_ORDER)
        {
            if (!Authorized(RoleType.SystemManager))
            {
                return(Error(Loc.Dic.error_no_permission));
            }

            IEnumerable <Budgets_Allocations> allocationsList;

            using (BudgetsRepository budgetsRepository = new BudgetsRepository(CurrentUser.CompanyId))
                using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                {
                    allocationsList = allocationsRep.GetList("Budgets_AllocationToMonth").Where(x => x.BudgetId == id);

                    allocationsList = Pagination(allocationsList, page, sortby, order);

                    ViewBag.BudgetId = id;
                    ViewBag.Year     = budgetsRepository.GetEntity(id).Year;
                    return(View(allocationsList.ToList()));
                }
        }
        public ActionResult Create()
        {
            return Error(Loc.Dic.Error_NoPermission);
            if (Authorized(RoleType.SystemManager))
            {
                using (BudgetsRepository budgetRep = new BudgetsRepository(CurrentUser.CompanyId))
                using (BudgetsExpensesRepository expensesRep = new BudgetsExpensesRepository())
                using (ParentProjectsRepository projectsRep = new ParentProjectsRepository())
                using (SubProjectsRepository subProjectsRep = new SubProjectsRepository())
                {
                    List<SelectListItemDB> budgetsList = budgetRep.GetList()
                        .Where(budget => budget.CompanyId == CurrentUser.CompanyId && budget.Year >= (DateTime.Now.Year - 1))
                        .Select(a => new { Id = a.Id, Name = a.Year })
                        .AsEnumerable()
                        .Select(x => new SelectListItemDB() { Id = x.Id, Name = x.Name.ToString() })
                        .ToList();

                    List<SelectListItemDB> projectsList = projectsRep.GetList()
                        .Where(project => project.CompanyId == CurrentUser.CompanyId && project.IsActive)
                        .Select(x => new SelectListItemDB() { Id = x.Id, Name = x.Name })
                        .ToList();

                    List<SelectListItemDB> subProjectsList = subProjectsRep.GetList()
                       .Where(subProject => subProject.CompanyId == CurrentUser.CompanyId && subProject.IsActive)
                       .Select(x => new SelectListItemDB() { Id = x.Id, Name = x.Name })
                       .ToList();

                    ViewBag.BudgetId = new SelectList(budgetsList, "Id", "Name");
                    ViewBag.ParentProjectId = new SelectList(projectsList, "Id", "Name");
                    ViewBag.SubProjectId = new SelectList(subProjectsList, "Id", "Name");
                }

                return View();
            }
            else
            {
                return Error(Loc.Dic.error_no_permission);
            }
        }
Exemple #29
0
            public void ReturnsBudgetFromContext()
            {
                // Arrange.
                this.budgetId = 1;
                this.userId   = 1;

                // Act.
                Budget actual;

                using (CheckbookContext context = new CheckbookContext(this.dbContextOptions))
                {
                    BudgetsRepository repository = new BudgetsRepository(context);
                    actual = repository.Get(this.budgetId, this.userId);
                }

                // Assert.
                Budget expected = this.entities.ElementAt(0);

                Assert.AreEqual(expected.Id, actual.Id, "The ID for the entity should match.");
                Assert.AreEqual(expected.Name, actual.Name, "The name for the entity should match.");
                Assert.AreEqual(expected.UserId, actual.UserId, "The user ID for the entity should match.");
            }
Exemple #30
0
            public void ReturnsBudgetsFromContext()
            {
                // Act.
                List <Budget> actualList;

                using (CheckbookContext context = new CheckbookContext(this.dbContextOptions))
                {
                    BudgetsRepository repository = new BudgetsRepository(context);
                    actualList = repository.GetAll(this.userId).ToList();
                }

                // Assert.
                Assert.AreEqual(this.entities.Count(), actualList.Count(), "The entity count should match.");

                Budget expected = this.entities.ElementAt(0);
                Budget actual   = actualList.ElementAt(0);
                string index    = "first";

                Assert.AreEqual(expected.Id, actual.Id, $"The ID for the {index} entity should match.");
                Assert.AreEqual(expected.Name, actual.Name, $"The name for the {index} entity should match.");
                Assert.AreEqual(expected.UserId, actual.UserId, $"The user ID for the {index} entity should match.");
            }
        public ActionResult BudgetBaskets(int id = 0, int page = FIRST_PAGE, string sortby = DEFAULT_SORT, string order = DEFAULT_DESC_ORDER)
        {
            if (!Authorized(RoleType.SystemManager))
            {
                return(Error(Loc.Dic.error_no_permission));
            }

            IEnumerable <Budgets_Baskets> baskets;
            Budgets_BasketsToAllocation   per = new Budgets_BasketsToAllocation();

            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
                using (BudgetsPermissionsRepository permissionsRep = new BudgetsPermissionsRepository())
                {
                    baskets = permissionsRep.GetList("Budgets_BasketsToAllocation").Where(x => x.CompanyId == CurrentUser.CompanyId);

                    baskets = Pagination(baskets, page, sortby, order, true);

                    ViewBag.budgetId = id;
                    Budget budget = budgetsRep.GetList().SingleOrDefault(x => x.Id == id);
                    ViewBag.budgetYear = budget.Year;
                    ViewBag.budgetId   = budget.Id;
                    return(View(baskets.ToList()));
                }
        }
        public ActionResult Import(HttpPostedFileBase file, int? id, string name, int? year, string budgetType)
        {
            if (!Authorized(RoleType.SystemManager)) return Error(Loc.Dic.error_no_permission);
            if (file != null && file.ContentLength <= 0) return Error(Loc.Dic.error_invalid_form);
            if (string.IsNullOrEmpty(budgetType))
                return Error(Loc.Dic.Error_chooseMonthelyOrYearlyBudget);
            if (!(budgetType == "Month" || budgetType == "Year"))
                return Error(Loc.Dic.Error_no_budgetType);

            if (id.HasValue)
            {
                string moved = Interfaces.ImportBudget(file.InputStream, CurrentUser.CompanyId, id.Value, budgetType);
                if (moved == "OK") return RedirectToAction("index");
                else return Error(moved);
            }
            else if (year.HasValue)
            {
                if (year.Value > DateTime.Now.Year + 10 || year.Value < DateTime.Now.Year - 1)
                    return Error(Loc.Dic.error_invalid_budget_year);

                using (BudgetsRepository budgetsRepository = new BudgetsRepository(CurrentUser.CompanyId))
                {
                    Budget newBudget = new Budget();
                    newBudget.Name = name;
                    newBudget.Year = year.Value;
                    newBudget.CompanyId = CurrentUser.CompanyId;
                    newBudget.IsActive = false;
                    budgetsRepository.Create(newBudget);
                    string moved = Interfaces.ImportBudget(file.InputStream, CurrentUser.CompanyId, newBudget.Id, budgetType);
                    if (moved == "OK") return RedirectToAction("index");
                    else return Error(moved);
                }

            }
            return Error(Loc.Dic.error_invalid_form);
        }
        public ActionResult EditAllocations(PermissionAllocationsModel model)
        {
            if (!Authorized(RoleType.SystemManager))
            {
                return(Error(Loc.Dic.error_no_permission));
            }

            Budgets_Baskets                    permissionFromDB;
            List <Budgets_Allocations>         existingPermissionAllocations;
            List <Budgets_BasketsToAllocation> existingPermissionToAllocations;

            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
                using (BudgetsPermissionsRepository permissionsRep = new BudgetsPermissionsRepository())
                    using (BasketsToAllocationsRepository permissionsAllocationsRep = new BasketsToAllocationsRepository())
                        using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                        {
                            permissionFromDB = permissionsRep.GetEntity(model.Basket.Id);
                            //TODO: Error gets ALL pemissions from DB
                            existingPermissionAllocations   = permissionsAllocationsRep.GetList().Where(x => x.BasketId == permissionFromDB.Id).Select(y => y.Budgets_Allocations).ToList();
                            existingPermissionToAllocations = permissionsAllocationsRep.GetList().Where(x => x.BasketId == permissionFromDB.Id).ToList();

                            if (permissionFromDB == null)
                            {
                                return(Error(Loc.Dic.error_database_error));
                            }

                            if (permissionFromDB.CompanyId != CurrentUser.CompanyId)
                            {
                                return(Error(Loc.Dic.error_no_permission));
                            }

                            Budget budgetFromDB = budgetsRep.GetEntity(model.BudgetAllocations.Budget.Id);

                            if (budgetFromDB == null)
                            {
                                return(Error(Loc.Dic.error_database_error));
                            }

                            if (budgetFromDB.CompanyId != CurrentUser.CompanyId)
                            {
                                return(Error(Loc.Dic.error_no_permission));
                            }

                            foreach (var allocation in model.BudgetAllocations.PermissionAllocations)
                            {
                                if (allocation.IsActive)
                                {
                                    if (!existingPermissionAllocations.Any(x => x.Id == allocation.Allocation.BudgetsAllocationId))
                                    {
                                        allocation.Allocation.BudgetId = budgetFromDB.Id;
                                        allocation.Allocation.BasketId = permissionFromDB.Id;
                                        if (!permissionsAllocationsRep.Create(allocation.Allocation))
                                        {
                                            return(Error(Loc.Dic.error_database_error));
                                        }
                                    }
                                }
                                else
                                {
                                    if (existingPermissionAllocations.Any(x => x.Id == allocation.Allocation.BudgetsAllocationId))
                                    {
                                        permissionsAllocationsRep.Delete(allocation.Allocation.Id);
                                    }
                                }
                            }

                            return(RedirectToAction("BudgetBaskets", new { id = budgetFromDB.Id }));
                        }
        }
        public ActionResult Index(int page = FIRST_PAGE, string sortby = DEFAULT_SORT, string order = DEFAULT_DESC_ORDER)
        {
            if (!Authorized(RoleType.SystemManager))
                return Error(Loc.Dic.error_no_permission);

            IEnumerable<Budget> budgets;
            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
            {
                budgets = budgetsRep.GetList().Where(x => x.CompanyId == CurrentUser.CompanyId);

                budgets = Pagination(budgets, page, sortby, order);

                return View(budgets.ToList());
            }
        }
        public ActionResult Edit(Budgets_Allocations Budgets_Allocations)
        {
            return Error(Loc.Dic.error_no_permission);
            if (Authorized(RoleType.SystemManager))
            {
                if (ModelState.IsValid)
                {
                    Budgets_Allocations allocation;
                    Budgets_Incomes income;
                    Budgets_Expenses expense;

                    using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
                    using (BudgetsIncomesRepository incomesRep = new BudgetsIncomesRepository())
                    using (BudgetsExpensesRepository expensesRep = new BudgetsExpensesRepository())
                    using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                    using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId))
                    {
                        allocation = allocationsRep.GetEntity(Budgets_Allocations.Id);

                        if (allocation != null)
                        {
                            if (allocation.CompanyId == CurrentUser.CompanyId)
                            {
                                income = incomesRep.GetEntity(Budgets_Allocations.IncomeId.Value);
                                expense = expensesRep.GetEntity(Budgets_Allocations.ExpenseId.Value);

                                if (income != null && expense != null)
                                {
                                    if (income.BudgetId == allocation.BudgetId && expense.BudgetId == allocation.BudgetId)
                                    {
                                        decimal? totalUsed;
                                        decimal? allocatedToExpense;
                                        decimal? allocatedToIncome;

                                        totalUsed = 0; //totalUsed = ordersRep.GetList()
                                        //    .Where(order => order.BudgetAllocationId == Budgets_Allocations.Id && order.StatusId >= (int)StatusType.ApprovedPendingInvoice)
                                        //    .Sum(x => (decimal?)x.Price);

                                        if ((totalUsed ?? 0) > Budgets_Allocations.CompanyId)//if ((totalUsed ?? 0) > Budgets_Allocations.Amount)
                                            return Error(Loc.Dic.error_allocations_amount_is_used);

                                        allocatedToIncome = allocationsRep.GetList()
                                             .Where(x => x.IncomeId == income.Id && x.Id != Budgets_Allocations.Id)
                                             .Sum(alloc => (decimal?)alloc.CompanyId);//.Sum(alloc => (decimal?)alloc.Amount);

                                        if ((allocatedToIncome ?? 0) + Budgets_Allocations.CompanyId > income.Amount)//if ((allocatedToIncome ?? 0) + Budgets_Allocations.Amount > income.Amount)
                                            return Error(Loc.Dic.error_income_full_allocation);

                                        allocatedToExpense = allocationsRep.GetList()
                                            .Where(x => x.ExpenseId == expense.Id && x.Id != Budgets_Allocations.Id)
                                            .Sum(alloc => (decimal?)alloc.CompanyId);//.Sum(alloc => (decimal?)alloc.Amount);

                                        if ((allocatedToExpense ?? 0) + Budgets_Allocations.CompanyId > expense.Amount)//if ((allocatedToExpense ?? 0) + Budgets_Allocations.Amount > expense.Amount)
                                            return Error(Loc.Dic.error_expenses_full_allocation);

                                        allocation.IncomeId = Budgets_Allocations.IncomeId;
                                        allocation.ExpenseId = Budgets_Allocations.ExpenseId;
                                        allocation.CompanyId = Budgets_Allocations.CompanyId;//allocation.Amount = Budgets_Allocations.Amount;

                                        Budgets_Allocations update = allocationsRep.Update(allocation);

                                        if (update != null)
                                            return RedirectToAction("Index");
                                        else
                                            return Error(Loc.Dic.error_allocations_get_error);
                                    }
                                    else
                                    {
                                        return Error(Loc.Dic.error_invalid_form);

                                    }
                                }
                                else
                                {
                                    return Error(Loc.Dic.error_database_error);
                                }
                            }
                            else
                            {
                                return Error(Loc.Dic.error_no_permission);
                            }
                        }
                        else
                        {
                            return Error(Loc.Dic.error_allocations_get_error);
                        }
                    }
                }
                else
                {
                    return Error(ModelState);
                }
            }
            else
            {
                return Error(Loc.Dic.error_no_permission);
            }
        }
Exemple #36
0
        //public static string ImportYearBudget(Stream stream, int companyId, int budgetId)
        //{
        //    const int EXTERNALID = 0;
        //    const int NAME = 1;
        //    const int AMOUNT = 2;
        //    const int JANUARY = 1;
        //    const int FEBRUARY = 2;
        //    const int MONTHESINYEAR = 12;
        //    List<Budgets_Allocations> newAllocations = new List<Budgets_Allocations>();
        //    Dictionary<int, decimal> tempAmountList = new Dictionary<int, decimal>();
        //    byte[] fileBytes = new byte[stream.Length];
        //    stream.Read(fileBytes, 0, Convert.ToInt32(stream.Length));
        //    string fileContent = System.Text.Encoding.Default.GetString(fileBytes);
        //    string[] fileLines = fileContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
        //    int firstValuesLine = 0;
        //    bool noErros = true;
        //    string errorType = String.Empty;
        //    using (AllocationMonthsRepository allocationMonthRepository = new AllocationMonthsRepository())
        //    using (BudgetsRepository budgetsRepository = new BudgetsRepository())
        //    using (AllocationRepository allocationRep = new AllocationRepository())
        //    {
        //        for (int i = firstValuesLine; i < fileLines.Length; i++)
        //        {
        //            string[] lineValues = fileLines[i].Split('\t');
        //            for (int vIndex = 0; vIndex < lineValues.Length; vIndex++)
        //            {
        //                lineValues[vIndex] = lineValues[vIndex].Replace("\"", "");
        //            }
        //            if (!(int.Parse(lineValues[EXTERNALID]) > 0))
        //            {
        //                errorType = Loc.Dic.error_invalid_form;
        //                break;
        //            }
        //            if (lineValues[NAME] == null)
        //            {
        //                errorType = Loc.Dic.error_invalid_form;
        //                break;
        //            }
        //            if (!(decimal.Parse(lineValues[AMOUNT]) >= 0))
        //            {
        //                errorType = Loc.Dic.error_invalid_form;
        //                break;
        //            }
        //            Budget budget = budgetsRepository.GetList().SingleOrDefault(x => x.Id == budgetId);
        //            Budgets_Allocations newAllocation;
        //            if (lineValues[EXTERNALID].Length != 8 || lineValues[NAME].Length > 100)
        //                return Loc.Dic.Error_FileParseError;
        //            newAllocation = new Budgets_Allocations()
        //            {
        //                CompanyId = companyId,
        //                BudgetId = budget.Id,
        //                ExternalId = lineValues[EXTERNALID],
        //                Name = lineValues[NAME],
        //                CreationDate = DateTime.Now
        //            };
        //            if (allocationRep.GetList().SingleOrDefault(x => x.CompanyId == companyId && x.ExternalId == newAllocation.ExternalId && x.BudgetId == budgetId) == null)
        //            {
        //                allocationRep.Create(newAllocation);
        //                tempAmountList.Add(newAllocation.Id, decimal.Parse(lineValues[AMOUNT]));
        //            }
        //            else
        //            {
        //                Budgets_Allocations existingAllocation = allocationRep.GetList().SingleOrDefault(x => x.CompanyId == companyId && x.ExternalId == newAllocation.ExternalId && x.BudgetId == budgetId);
        //                existingAllocation.Name = newAllocation.Name;
        //                allocationRep.Update(existingAllocation);
        //                tempAmountList.Add(existingAllocation.Id, decimal.Parse(lineValues[AMOUNT]));
        //            }
        //        }
        //        List<Budgets_AllocationToMonth> toAddAllocationMonthList = new List<Budgets_AllocationToMonth>();
        //        foreach (var item in tempAmountList)
        //        {
        //            if (allocationMonthRepository.GetList().Where(x => x.AllocationId == item.Key).SingleOrDefault(x => x.MonthId == JANUARY) == null)
        //            {
        //                Budgets_AllocationToMonth toAddallocationMonth = new Budgets_AllocationToMonth();
        //                toAddallocationMonth.AllocationId = item.Key;
        //                toAddallocationMonth.MonthId = JANUARY;
        //                toAddallocationMonth.Amount = item.Value;
        //                toAddAllocationMonthList.Add(toAddallocationMonth);
        //            }
        //            else
        //            {
        //                Budgets_AllocationToMonth existingAllocationMonth = allocationMonthRepository.GetList().Where(x => x.AllocationId == item.Key).SingleOrDefault(x => x.MonthId == JANUARY);
        //                existingAllocationMonth.Amount = item.Value;
        //                allocationMonthRepository.Update(existingAllocationMonth);
        //            }
        //            for (int i = FEBRUARY; i <= MONTHESINYEAR; i++)
        //            {
        //                Budgets_AllocationToMonth toAddZeroallocationMonth = new Budgets_AllocationToMonth();
        //                toAddZeroallocationMonth.AllocationId = item.Key;
        //                toAddZeroallocationMonth.MonthId = i;
        //                toAddZeroallocationMonth.Amount = 0;
        //                toAddAllocationMonthList.Add(toAddZeroallocationMonth);
        //            }
        //        }
        //        allocationMonthRepository.AddList(toAddAllocationMonthList);
        //    }
        //    if (!noErros) return errorType;
        //    return "OK";
        //}
        public static string ImportBudget(Stream stream, int companyId, int budgetId, string budgetType)
        {
            bool noErros = true;
            string errorType = String.Empty;
            Budget budget;
            using (BudgetsRepository budgetsRepository = new BudgetsRepository(companyId))
            {
                budget = budgetsRepository.GetList().SingleOrDefault(x => x.Id == budgetId);
            }

            List<ImportedAllocation> importedAllocations = new List<ImportedAllocation>();
            List<Budgets_Allocations> newAllocations = new List<Budgets_Allocations>();
            List<Budgets_AllocationToMonth> newAllocationMonths = new List<Budgets_AllocationToMonth>();

            byte[] fileBytes = new byte[stream.Length];
            stream.Read(fileBytes, 0, Convert.ToInt32(stream.Length));
            string fileContent = System.Text.Encoding.Default.GetString(fileBytes);

            string[] fileLines = fileContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            int firstValuesLine = new int();

            if (!(budgetType == "Month" || budgetType == "Year"))
                return Loc.Dic.Error_no_budgetType;

            if (budgetType == "Month")
                firstValuesLine = 3;
            else if (budgetType == "Year")
                firstValuesLine = 0;

            for (int i = firstValuesLine; i < fileLines.Length; i++)
            {
                string[] lineValues = fileLines[i].Split('\t');
                for (int vIndex = 0; vIndex < lineValues.Length; vIndex++)
                {
                    lineValues[vIndex] = lineValues[vIndex].Replace("\"", "");
                }

                Budgets_Allocations newAllocation;
                int sortingCode;

                if (lineValues[1].Length > 8 || lineValues[2].Length > 100) return Loc.Dic.Error_FileParseError;
                if (!int.TryParse(lineValues[0], out sortingCode)) return Loc.Dic.Error_FileParseError;

                newAllocation = new Budgets_Allocations()
                {
                    SortingCode = sortingCode,
                    ExternalId = lineValues[1],
                    Name = lineValues[2],
                    BudgetId = budget.Id,
                    CompanyId = companyId,
                    CreationDate = DateTime.Now,
                    IncomeId = null,
                    ExpenseId = null
                };

                List<Budgets_AllocationToMonth> allocationMonthes = new List<Budgets_AllocationToMonth>();
                for (int month = 1, valueIndex = 3; month <= 12; month++, valueIndex += 2)
                {
                    string monthAmountString = lineValues[valueIndex];
                    if (String.IsNullOrEmpty(monthAmountString))
                    {
                        monthAmountString = "0";
                    }

                    decimal amount;
                    if (!Decimal.TryParse(monthAmountString, out amount))
                        return Loc.Dic.Error_FileParseError;

                    Budgets_AllocationToMonth newAllocationMonth = new Budgets_AllocationToMonth()
                    {
                        AllocationId = 0,
                        MonthId = month,
                        Amount = amount < 0 ? 0 : amount
                    };

                    allocationMonthes.Add(newAllocationMonth);
                }

                importedAllocations.Add(new ImportedAllocation()
                {
                    isExistingAllocation = false,
                    Allocation = newAllocation,
                    AllocationMonthes = allocationMonthes
                });
            }

            bool amountIsInvalid = false;
            StringBuilder builder = new StringBuilder();

            using (AllocationRepository allocationsRep = new AllocationRepository(companyId))
            using (AllocationMonthsRepository allocationMonthsRep = new AllocationMonthsRepository())
            using (BudgetsRepository budgetsRep = new BudgetsRepository(companyId))
            {
                foreach (var item in importedAllocations)
                {
                    Budgets_Allocations existingAllocation = allocationsRep.GetList().SingleOrDefault(x => x.CompanyId == companyId && x.ExternalId == item.Allocation.ExternalId && x.BudgetId == budgetId);
                    bool allocationExists = existingAllocation != null;

                    if (allocationExists)
                    {
                        item.isExistingAllocation = true;
                        existingAllocation.Name = item.Allocation.Name;
                        item.Allocation = existingAllocation;

                        foreach (var allocationMonth in item.AllocationMonthes)
                        {
                            Budgets_AllocationToMonth existingMonth = existingAllocation.Budgets_AllocationToMonth.SingleOrDefault(x => x.MonthId == allocationMonth.MonthId);

                            if (allocationMonth.Amount < existingMonth.Amount)
                            {
                                decimal totalUsed = existingMonth
                                    .Budgets_Allocations
                                    .Orders_OrderToAllocation
                                    .Where(x => x.MonthId == existingMonth.MonthId && x.Order.StatusId >= (int)StatusType.PartiallyApproved)
                                    .Sum(x => x.Amount);

                                if (allocationMonth.Amount < totalUsed)
                                {
                                    if (!amountIsInvalid)
                                    {
                                        amountIsInvalid = true;
                                        builder.AppendLine(Loc.Dic.error_imported_allocations_amount_is_used + ": ");
                                        builder.AppendLine();
                                    }
                                    builder.AppendLine(String.Format("{0} {1}-{2}: {3}: {4} > {5}: {6}", existingAllocation.DisplayName, Loc.Dic.Month, allocationMonth.MonthId, Loc.Dic.TheTotalUsed, totalUsed, Loc.Dic.TheNewAmount, allocationMonth.Amount));
                                }
                            }
                        }
                    }
                }

                if (amountIsInvalid)
                    return builder.ToString();

                List<Budgets_Allocations> existingAllocations;
                List<Budgets_Allocations> allocationsToDelete = new List<Budgets_Allocations>();

                budget = budgetsRep.GetList().SingleOrDefault(x => x.Id == budgetId);
                existingAllocations = budget.Budgets_Allocations.ToList();

                if (existingAllocations.Any())
                {
                    foreach (var existingAllocation in existingAllocations)
                    {
                        if (!importedAllocations.Any(x => x.Allocation.ExternalId == existingAllocation.ExternalId))
                        {
                            if (
                                existingAllocation.Budgets_BasketsToAllocation.Any() ||
                                existingAllocation.Orders_OrderToAllocation.Any()
                                )
                            {
                                existingAllocation.IsCanceled = true;
                            }
                            else
                            {
                                allocationsToDelete.Add(existingAllocation);
                            }
                        }
                    }

                    budgetsRep.Update(budget);

                    foreach (var item in allocationsToDelete)
                    {
                        allocationsRep.Delete(item.Id);
                    }
                }

                foreach (var item in importedAllocations)
                {
                    if (!noErros)
                        break;

                    if (item.isExistingAllocation)
                    {
                        for (int month = 1, valueIndex = 3; month <= 12; month++, valueIndex += 2)
                        {
                            //Budgets_AllocationToMonth UpdatedMonth = new Budgets_AllocationToMonth();
                            Budgets_AllocationToMonth existingMonth = item.Allocation.Budgets_AllocationToMonth.SingleOrDefault(x => x.MonthId == month);
                            Budgets_AllocationToMonth importedMonth = item.AllocationMonthes.Single(x => x.MonthId == month);

                            existingMonth.Amount = importedMonth.Amount;

                            //UpdatedMonth.Id = existingMonth.Id;
                            //UpdatedMonth.AllocationId = existingMonth.AllocationId;
                            //UpdatedMonth.MonthId = existingMonth.MonthId;
                            //UpdatedMonth.Amount = importedMonth.Amount;

                            //if (allocationMonthsRep.Update(UpdatedMonth) == null)
                            //{
                            //    noErros = false;
                            //    errorType = Loc.Dic.error_database_error;
                            //    break;
                            //}
                        }

                        if (allocationsRep.Update(item.Allocation) == null)
                        {
                            noErros = false;
                            errorType = Loc.Dic.error_database_error;
                            break;
                        }
                    }
                    else
                    {
                        foreach (var allocationMonth in item.AllocationMonthes)
                        {
                            item.Allocation.Budgets_AllocationToMonth.Add(allocationMonth);
                        }

                        if (!allocationsRep.Create(item.Allocation))
                        {
                            noErros = false;
                            errorType = Loc.Dic.error_database_error;
                            break;
                        }
                    }
                }
            }

            if (!noErros)
                return errorType;

            return "OK";
        }
Exemple #37
0
        public ActionResult Edit(CreateOrderModel model, string itemsString)
        {
            if (!Authorized(RoleType.OrdersWriter)) return Error(Loc.Dic.error_no_permission);
            if (!ModelState.IsValid) return Error(Loc.Dic.error_invalid_form);

            // Initializing needed temporary variables
            bool wasReturnedToCreator;
            bool allowExeeding = true;
            List<Orders_OrderToAllocation> AllocationsToCreate = new List<Orders_OrderToAllocation>();

            Order orderFromDatabase;
            List<Orders_OrderToItem> itemsFromEditForm = new List<Orders_OrderToItem>();
            List<Orders_OrderToItem> itemsToDelete = new List<Orders_OrderToItem>();
            List<Orders_OrderToItem> itemsToCreate = new List<Orders_OrderToItem>();
            List<Orders_OrderToItem> itemsToUpdate = new List<Orders_OrderToItem>();

            decimal totalOrderPrice;
            decimal totalAllocation;
            List<Budgets_Allocations> orderAllocations = new List<Budgets_Allocations>();

            using (OrdersRepository orderRep = new OrdersRepository(CurrentUser.CompanyId))
            {
                orderFromDatabase = orderRep.GetEntity(model.Order.Id, "Supplier", "Orders_OrderToItem", "Orders_OrderToAllocation", "Users_ApprovalRoutes.Users_ApprovalStep");
            }

            if (orderFromDatabase == null) return Error(Loc.Dic.error_order_not_found);
            if (orderFromDatabase.UserId != CurrentUser.UserId) return Error(Loc.Dic.error_no_permission);

            if (orderFromDatabase.StatusId != (int)StatusType.Pending && orderFromDatabase.StatusId != (int)StatusType.PendingOrderCreator) return Error(Loc.Dic.error_order_edit_after_approval);
            wasReturnedToCreator = orderFromDatabase.StatusId == (int)StatusType.PendingOrderCreator;

            itemsFromEditForm = ItemsFromString(itemsString, model.Order.Id);
            if (itemsFromEditForm == null) return Error(Loc.Dic.error_invalid_form);
            if (itemsFromEditForm.Count == 0) return Error(Loc.Dic.error_order_has_no_items);
            if (itemsFromEditForm.Count == 0) return Error(Loc.Dic.error_order_has_no_items);

            totalOrderPrice = (decimal.Floor(itemsFromEditForm.Sum(x => x.SingleItemPrice * x.Quantity) * 1000) / 1000);

            if (model.Allocations == null || model.Allocations.Where(x => x.IsActive).Count() == 0) return Error(Loc.Dic.error_invalid_form);
            model.Allocations = model.Allocations.Where(x => x.IsActive).ToList();
            totalAllocation = (decimal.Floor(model.Allocations.Sum(x => x.Amount) * 1000) / 1000);

            if (totalOrderPrice != totalAllocation) return Error(Loc.Dic.error_order_insufficient_allocation);

            using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId))
            using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
            {
                Budget currentBudget = budgetsRep.GetList().SingleOrDefault(x => x.CompanyId == CurrentUser.CompanyId && x.IsActive);
                if (currentBudget == null) return Error(Loc.Dic.error_database_error);
                model.Order.BudgetId = currentBudget.Id;

                int[] orderAllocationsIds = model.Allocations.Select(x => x.AllocationId).Distinct().ToArray();
                var allocationsData = allocationsRep.GetAllocationsData(orderAllocationsIds, StatusType.Pending);
                bool IsValidAllocations =
                    (allocationsData.Count == orderAllocationsIds.Length) &&
                    model.Allocations.All(x => (x.MonthId == null || (x.MonthId >= 1 && x.MonthId <= 12)) && x.Amount > 0);
                if (!IsValidAllocations) return Error(Loc.Dic.error_invalid_form);

                if (model.IsFutureOrder)
                {
                    foreach (var allocationData in allocationsData)
                    {
                        List<OrderAllocation> allocationMonths = model.Allocations.Where(x => x.AllocationId == allocationData.AllocationId).ToList();

                        foreach (var month in allocationMonths)
                        {
                            if (month.MonthId == DateTime.Now.Month)
                            {
                                OrderAllocation currentAllocation = model.Allocations.SingleOrDefault(x => x.AllocationId == allocationData.AllocationId);

                                var newAllocations = allocationsRep.GenerateOrderAllocations(allocationData, currentAllocation.Amount, allowExeeding, DateTime.Now.Month, orderFromDatabase.Id);
                                if (newAllocations == null) return Error(Loc.Dic.error_order_insufficient_allocation);

                                AllocationsToCreate.AddRange(newAllocations);
                            }
                            else
                            {
                                var monthData = allocationData.Months.SingleOrDefault(x => x.MonthId == month.MonthId);
                                if (!allowExeeding && month.Amount > monthData.RemainingAmount) return Error(Loc.Dic.error_order_insufficient_allocation);

                                Orders_OrderToAllocation newAllocation = new Orders_OrderToAllocation()
                                {
                                    AllocationId = allocationData.AllocationId,
                                    MonthId = month.MonthId.Value,
                                    Amount = month.Amount,
                                    OrderId = orderFromDatabase.Id
                                };

                                AllocationsToCreate.Add(newAllocation);
                            }
                        }
                    }
                }
                else
                {
                    foreach (var allocationData in allocationsData)
                    {
                        OrderAllocation currentAllocation = model.Allocations.SingleOrDefault(x => x.AllocationId == allocationData.AllocationId);

                        var newAllocations = allocationsRep.GenerateOrderAllocations(allocationData, currentAllocation.Amount, allowExeeding, DateTime.Now.Month, orderFromDatabase.Id);
                        if (newAllocations == null) return Error(Loc.Dic.error_order_insufficient_allocation);

                        AllocationsToCreate.AddRange(newAllocations);
                    }
                }
            }

            using (OrderToAllocationRepository orderAllocationRep = new OrderToAllocationRepository())
            {
                foreach (var item in orderFromDatabase.Orders_OrderToAllocation)
                {
                    orderAllocationRep.Delete(item.Id);
                }

                foreach (var item in AllocationsToCreate)
                {
                    orderAllocationRep.Create(item);
                }
            }

            foreach (var newItem in itemsFromEditForm)
            {
                Orders_OrderToItem existingItem = orderFromDatabase.Orders_OrderToItem.SingleOrDefault(x => x.ItemId == newItem.ItemId);

                if (existingItem != null)
                {
                    if (
                        existingItem.Quantity != newItem.Quantity ||
                        existingItem.SingleItemPrice != newItem.SingleItemPrice
                        )
                    {
                        newItem.Id = existingItem.Id;
                        itemsToUpdate.Add(newItem);
                    }
                }
                else
                {
                    itemsToCreate.Add(newItem);
                }
            }

            foreach (var existingItem in orderFromDatabase.Orders_OrderToItem)
            {
                Orders_OrderToItem newItem = itemsFromEditForm.SingleOrDefault(x => x.ItemId == existingItem.ItemId);

                if (newItem == null)
                {
                    itemsToDelete.Add(existingItem);
                }
            }

            bool noErrors = true;

            using (OrderToItemRepository orderToItemRep = new OrderToItemRepository())
            {
                foreach (var item in itemsToCreate)
                {
                    if (!orderToItemRep.Create(item) && noErrors)
                        noErrors = false;
                }
                foreach (var item in itemsToUpdate)
                {
                    if (orderToItemRep.Update(item) == null && noErrors)
                        noErrors = false;
                }
                foreach (var item in itemsToDelete)
                {
                    if (!orderToItemRep.Delete(item.Id) && noErrors)
                        noErrors = false;
                }

                using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId))
                {
                    if (!CurrentUser.OrdersApprovalRouteId.HasValue)
                    {
                        model.Order.NextOrderApproverId = null;
                        model.Order.StatusId = (int)StatusType.ApprovedPendingInvoice;
                    }
                    else
                    {
                        Users_ApprovalRoutes orderRoute = orderFromDatabase.Users_ApprovalRoutes; //routesRep.GetEntity(CurrentUser.OrdersApprovalRouteId.Value, "Users_ApprovalStep");
                        Users_ApprovalStep firstStep = orderRoute.Users_ApprovalStep.OrderBy(x => x.StepNumber).FirstOrDefault();

                        if (firstStep != null)
                        {
                            model.Order.ApprovalRouteId = orderRoute.Id;
                            model.Order.ApprovalRouteStep = firstStep.StepNumber;
                            model.Order.NextOrderApproverId = firstStep.UserId;
                            model.Order.StatusId = (int)StatusType.Pending;
                        }
                        else
                        {
                            model.Order.ApprovalRouteId = null;
                            model.Order.ApprovalRouteStep = null;
                            model.Order.NextOrderApproverId = null;
                            model.Order.StatusId = (int)StatusType.ApprovedPendingInvoice;
                        }
                    }

                    model.Order.CompanyId = orderFromDatabase.CompanyId;
                    model.Order.CreationDate = orderFromDatabase.CreationDate;
                    model.Order.SupplierId = orderFromDatabase.SupplierId;
                    model.Order.UserId = orderFromDatabase.UserId;
                    model.Order.OrderNumber = orderFromDatabase.OrderNumber;
                    model.Order.InvoiceNumber = orderFromDatabase.InvoiceNumber;
                    model.Order.InvoiceDate = orderFromDatabase.InvoiceDate;
                    model.Order.LastStatusChangeDate = DateTime.Now;
                    model.Order.ValueDate = orderFromDatabase.ValueDate;
                    model.Order.WasAddedToInventory = orderFromDatabase.WasAddedToInventory;
                    model.Order.IsFutureOrder = model.IsFutureOrder;

                    model.Order.Price = totalOrderPrice;

                    ordersRep.Update(model.Order);

                    model.Order = ordersRep.GetEntity(model.Order.Id, "User", "User1");
                }
            }

            if (noErrors)
            {
                int? historyActionId = null;
                historyActionId = (int)HistoryActions.Edited;
                Orders_History orderHistory = new Orders_History();
                using (OrdersHistoryRepository ordersHistoryRep = new OrdersHistoryRepository(CurrentUser.CompanyId, CurrentUser.UserId, model.Order.Id))
                    if (historyActionId.HasValue) ordersHistoryRep.Create(orderHistory, historyActionId.Value, model.NotesForApprover);

                if (wasReturnedToCreator)
                {
                    if (model.Order.NextOrderApproverId.HasValue)
                    {
                        SendNotifications.OrderPendingApproval(model.Order, Url);
                    }
                }

                return RedirectToAction("MyOrders");
            }
            else
                return Error(Loc.Dic.error_order_update_items_error);
        }
        public ActionResult Create(Budgets_Allocations Budgets_Allocations, int id = 0)
        {
            return(Error(Loc.Dic.error_no_permission));

            if (Authorized(RoleType.SystemManager))
            {
                if (ModelState.IsValid)
                {
                    Budget           budget;
                    Budgets_Incomes  income;
                    Budgets_Expenses expense;

                    using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
                        using (BudgetsIncomesRepository incomesRep = new BudgetsIncomesRepository())
                            using (BudgetsExpensesRepository expensesRep = new BudgetsExpensesRepository())
                                using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                                {
                                    budget = budgetsRep.GetEntity(id);

                                    if (budget != null)
                                    {
                                        if (budget.CompanyId == CurrentUser.CompanyId)
                                        {
                                            income  = incomesRep.GetEntity(Budgets_Allocations.IncomeId.Value);
                                            expense = expensesRep.GetEntity(Budgets_Allocations.ExpenseId.Value);

                                            if (income != null && expense != null)
                                            {
                                                if (income.BudgetId == budget.Id && expense.BudgetId == budget.Id)
                                                {
                                                    decimal?allocatedToExpense;
                                                    decimal?allocatedToIncome;

                                                    allocatedToIncome = allocationsRep.GetList()
                                                                        .Where(x => x.IncomeId == income.Id)
                                                                        .Sum(allocation => (decimal?)allocation.CompanyId);       //.Sum(allocation => (decimal?)allocation.Amount);

                                                    if ((allocatedToIncome ?? 0) + Budgets_Allocations.CompanyId > income.Amount) //if ((allocatedToIncome ?? 0) + Budgets_Allocations.Amount > income.Amount)
                                                    {
                                                        return(Error(Loc.Dic.error_income_full_allocation));
                                                    }

                                                    allocatedToExpense = allocationsRep.GetList()
                                                                         .Where(x => x.ExpenseId == expense.Id)
                                                                         .Sum(allocation => (decimal?)allocation.CompanyId);        //.Sum(allocation => (decimal?)allocation.Amount);

                                                    if ((allocatedToExpense ?? 0) + Budgets_Allocations.CompanyId > expense.Amount) //if ((allocatedToExpense ?? 0) + Budgets_Allocations.Amount > expense.Amount)
                                                    {
                                                        return(Error(Loc.Dic.error_expenses_full_allocation));
                                                    }

                                                    Budgets_Allocations.CompanyId = CurrentUser.CompanyId;
                                                    Budgets_Allocations.BudgetId  = budget.Id;
                                                    Budgets_Allocations.CompanyId = CurrentUser.CompanyId;

                                                    if (allocationsRep.Create(Budgets_Allocations))
                                                    {
                                                        return(RedirectToAction("Index"));
                                                    }
                                                    else
                                                    {
                                                        return(Error(Loc.Dic.error_database_error));
                                                    }
                                                }
                                                else
                                                {
                                                    return(Error(Loc.Dic.error_invalid_form));
                                                }
                                            }
                                            else
                                            {
                                                return(Error(Loc.Dic.error_database_error));
                                            }
                                        }
                                        else
                                        {
                                            return(Error(Loc.Dic.error_no_permission));
                                        }
                                    }
                                    else
                                    {
                                        return(Error(Loc.Dic.error_database_error));
                                    }
                                }
                }
                else
                {
                    return(Error(ModelState));
                }
            }
            else
            {
                return(Error(Loc.Dic.error_no_permission));
            }
        }
Exemple #39
0
        public ActionResult Create(CreateOrderModel model)
        {
            /// Validating user input
            if (!Authorized(RoleType.OrdersWriter)) return Error(Loc.Dic.error_no_permission);
            if (!ModelState.IsValid) return Error(Loc.Dic.error_invalid_form);
            if (String.IsNullOrEmpty(model.ItemsString)) return Error(Loc.Dic.error_invalid_form);
            List<Orders_OrderToItem> ItemsList = ItemsFromString(model.ItemsString, 0);
            if (ItemsList == null || ItemsList.Count == 0) return Error(Loc.Dic.error_invalid_form);
            if (model.IsFutureOrder && !Authorized(RoleType.FutureOrderWriter)) return Error(Loc.Dic.Error_NoPermission);
            if (model.Allocations == null || model.Allocations.Where(x => x.IsActive).Count() == 0) return Error(Loc.Dic.error_invalid_form);
            model.Allocations = model.Allocations.Where(x => x.IsActive).ToList();
            decimal totalOrderPrice = (decimal.Floor(ItemsList.Sum(x => x.SingleItemPrice * x.Quantity) * 1000) / 1000);
            decimal totalAllocation = (decimal.Floor(model.Allocations.Sum(x => x.Amount) * 1000) / 1000);
            if (totalOrderPrice != totalAllocation) return Error(Loc.Dic.error_order_insufficient_allocation);

            // Initializing needed temporary variables
            bool allowExeeding = true;
            List<Orders_OrderToAllocation> AllocationsToCreate = new List<Orders_OrderToAllocation>();

            // Setting order properties
            model.Order.UserId = CurrentUser.UserId;
            model.Order.Price = totalOrderPrice;
            model.Order.IsFutureOrder = model.IsFutureOrder;

            using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
            using (ApprovalRoutesRepository routesRep = new ApprovalRoutesRepository(CurrentUser.CompanyId))
            {
                Budget currentBudget = budgetsRep.GetList().SingleOrDefault(x => x.IsActive);
                if (currentBudget == null) return Error(Loc.Dic.error_database_error);
                model.Order.BudgetId = currentBudget.Id;

                int[] orderAllocationsIds = model.Allocations.Select(x => x.AllocationId).Distinct().ToArray();
                var allocationsData = allocationsRep.GetAllocationsData(orderAllocationsIds, StatusType.Pending);
                bool IsValidAllocations =
                    (allocationsData.Count == orderAllocationsIds.Length) &&
                    model.Allocations.All(x => (x.MonthId == null || (x.MonthId >= 1 && x.MonthId <= 12)) && x.Amount > 0);
                if (!IsValidAllocations) return Error(Loc.Dic.error_invalid_form);

                if (model.IsFutureOrder)
                {
                    foreach (var allocationData in allocationsData)
                    {
                        List<OrderAllocation> allocationMonths = model.Allocations.Where(x => x.AllocationId == allocationData.AllocationId).ToList();

                        foreach (var month in allocationMonths)
                        {
                            if (month.MonthId == DateTime.Now.Month)
                            {
                                OrderAllocation currentAllocation = model.Allocations.SingleOrDefault(x => x.AllocationId == allocationData.AllocationId);

                                var newAllocations = allocationsRep.GenerateOrderAllocations(allocationData, currentAllocation.Amount, allowExeeding, DateTime.Now.Month);
                                if (newAllocations == null) return Error(Loc.Dic.error_order_insufficient_allocation);

                                AllocationsToCreate.AddRange(newAllocations);
                            }
                            else
                            {
                                var monthData = allocationData.Months.SingleOrDefault(x => x.MonthId == month.MonthId);
                                if (!allowExeeding && month.Amount > monthData.RemainingAmount) return Error(Loc.Dic.error_order_insufficient_allocation);

                                Orders_OrderToAllocation newAllocation = new Orders_OrderToAllocation()
                                {
                                    AllocationId = allocationData.AllocationId,
                                    MonthId = month.MonthId.Value,
                                    Amount = month.Amount,
                                    OrderId = 0
                                };

                                AllocationsToCreate.Add(newAllocation);
                            }
                        }
                    }
                }
                else
                {
                    foreach (var allocationData in allocationsData)
                    {
                        OrderAllocation currentAllocation = model.Allocations.SingleOrDefault(x => x.AllocationId == allocationData.AllocationId);

                        var newAllocations = allocationsRep.GenerateOrderAllocations(allocationData, currentAllocation.Amount, allowExeeding, DateTime.Now.Month);
                        if (newAllocations == null) return Error(Loc.Dic.error_order_insufficient_allocation);

                        AllocationsToCreate.AddRange(newAllocations);
                    }
                }

                if (!CurrentUser.OrdersApprovalRouteId.HasValue)
                {
                    model.Order.NextOrderApproverId = null;
                    model.Order.StatusId = (int)StatusType.ApprovedPendingInvoice;
                }
                else
                {
                    Users_ApprovalRoutes orderRoute = routesRep.GetEntity(CurrentUser.OrdersApprovalRouteId.Value, "Users_ApprovalStep");
                    Users_ApprovalStep firstStep = orderRoute.Users_ApprovalStep.OrderBy(x => x.StepNumber).FirstOrDefault();

                    if (firstStep != null)
                    {
                        model.Order.ApprovalRouteId = orderRoute.Id;
                        model.Order.ApprovalRouteStep = firstStep.StepNumber;
                        model.Order.NextOrderApproverId = firstStep.UserId;
                        model.Order.StatusId = (int)StatusType.Pending;
                    }
                    else
                    {
                        model.Order.ApprovalRouteStep = null;
                        model.Order.NextOrderApproverId = null;
                        model.Order.StatusId = (int)StatusType.ApprovedPendingInvoice;
                    }
                }
            }

            using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId))
            using (OrderToItemRepository orderToItemRep = new OrderToItemRepository())
            using (OrderToAllocationRepository orderAllocationsRep = new OrderToAllocationRepository())
            {
                bool creationError = false;
                if (!ordersRep.Create(model.Order)) return Error(Loc.Dic.error_orders_create_error);

                model.Order = ordersRep.GetEntity(model.Order.Id, "User", "User1");

                foreach (Orders_OrderToItem item in ItemsList)
                {
                    item.OrderId = model.Order.Id;

                    if (!orderToItemRep.Create(item))
                    {
                        creationError = true;
                        break;
                    }
                }

                foreach (var allocation in AllocationsToCreate)
                {
                    allocation.OrderId = model.Order.Id;

                    if (!orderAllocationsRep.Create(allocation))
                    {
                        creationError = true;
                        break;
                    }
                }

                if (creationError)
                {
                    ordersRep.Delete(model.Order.Id);
                    return Error(Loc.Dic.error_orders_create_error);
                }
            }

            using (OrdersHistoryRepository ordersHistoryRepository = new OrdersHistoryRepository(CurrentUser.CompanyId, CurrentUser.UserId, model.Order.Id))
            {
                Orders_History orderHis = new Orders_History();
                ordersHistoryRepository.Create(orderHis, (int)HistoryActions.Created, model.NotesForApprover);
            }

            if (model.Order.NextOrderApproverId.HasValue)
            {
                SendNotifications.OrderPendingApproval(model.Order, Url);
            }

            return RedirectToAction("MyOrders");
        }
Exemple #40
0
        public ActionResult SearchForm(OrdersSearchValuesModel model, bool isExpanding, bool isCollapsed, int? userId = null, int? statusId = null, int? supplierId = null, bool hideUserField = false, bool hideStatusField = false, bool hideSupplierField = false)
        {
            if (model == null) model = new OrdersSearchValuesModel();

            using (UsersRepository usersRep = new UsersRepository(CurrentUser.CompanyId))
            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
            using (SuppliersRepository suppliersRep = new SuppliersRepository(CurrentUser.CompanyId))
            using (OrderStatusesRepository statusesRep = new OrderStatusesRepository())
            using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
            {
                List<SelectListItemDB> usersAsSelectItems = new List<SelectListItemDB>() { new SelectListItemDB() { Id = -1, Name = Loc.Dic.AllUsersOption } };
                usersAsSelectItems.AddRange(usersRep.GetList().Select(x => new SelectListItemDB() { Id = x.Id, Name = x.FirstName + " " + x.LastName }));
                model.UsersList = new SelectList(usersAsSelectItems, "Id", "Name");

                List<SelectListItemDB> budgetsAsSelectItems = new List<SelectListItemDB>() { new SelectListItemDB() { Id = -1, Name = Loc.Dic.AllBudgetsOption } };
                budgetsAsSelectItems.AddRange(budgetsRep.GetList().AsEnumerable().Select(x => new SelectListItemDB() { Id = x.Id, Name = "(" + x.Year + ") " + x.Name }));
                model.BudgetsList = new SelectList(budgetsAsSelectItems, "Id", "Name");

                List<Supplier> suppliersSelectList = new List<Supplier>() { new Supplier() { Id = -1, Name = Loc.Dic.AllSuppliersOption } };
                suppliersSelectList.AddRange(suppliersRep.GetList().OrderByDescending(x => x.Name).ToList());
                model.SuppliersList = new SelectList(suppliersSelectList, "Id", "Name");

                List<Orders_Statuses> statusesSelectList = new List<Orders_Statuses>() { new Orders_Statuses() { Id = -1, Name = Loc.Dic.AllStatusesOption } };
                statusesSelectList.AddRange(statusesRep.GetList().ToList());
                model.StatusesList = new SelectList(statusesSelectList, "Id", "Name");

                List<SelectListStringItem> allocationsSelectList = new List<SelectListStringItem>() { new SelectListStringItem() { Id = "-1", Name = Loc.Dic.AllAllocationsOption } };
                allocationsSelectList.AddRange(allocationsRep.GetList().GroupBy(x => x.ExternalId).AsEnumerable().Select(x => new SelectListStringItem() { Id = x.First().ExternalId, Name = x.First().DisplayName }).ToList());
                model.AllocationsList = new SelectList(allocationsSelectList, "Id", "Name");
            }

            ViewBag.IsExpanding = isExpanding;
            ViewBag.IsCollapsed = isCollapsed;
            ViewBag.UserId = userId;
            ViewBag.StatusId = statusId;
            ViewBag.SupplierId = supplierId;
            ViewBag.HideUserField = hideUserField;
            ViewBag.HideStatusField = hideStatusField;
            ViewBag.HideSupplierField = hideSupplierField;
            return PartialView(model);
        }
        public ActionResult Create(Budgets_Expenses budgets_expenses)
        {
            return Error(Loc.Dic.Error_NoPermission);
            if (Authorized(RoleType.SystemManager))
            {
                if (ModelState.IsValid)
                {
                    Budget budget;
                    Projects_ParentProject project;
                    Projects_SubProject subProject;

                    using (BudgetsRepository budgetRep = new BudgetsRepository(CurrentUser.CompanyId))
                    using (ParentProjectsRepository projectsRep = new ParentProjectsRepository())
                    using (SubProjectsRepository subProjectsRep = new SubProjectsRepository())
                    {
                        budget = budgetRep.GetEntity(budgets_expenses.BudgetId);
                        project = projectsRep.GetEntity(budgets_expenses.ParentProjectId.Value);
                        subProject = subProjectsRep.GetEntity(budgets_expenses.SubProjectId.Value);
                    }

                    if (budget != null && project != null && subProject != null)
                    {
                        if (budget.CompanyId == CurrentUser.CompanyId && project.CompanyId == CurrentUser.CompanyId && subProject.CompanyId == CurrentUser.CompanyId)
                        {
                            if (project.IsActive && subProject.IsActive)
                            {
                                bool wasCreated;
                                budgets_expenses.CompanyId = CurrentUser.CompanyId;

                                using (BudgetsExpensesRepository expensesRep = new BudgetsExpensesRepository())
                                {
                                    wasCreated = expensesRep.Create(budgets_expenses);
                                }

                                if (wasCreated)
                                    return RedirectToAction("Index");
                                else
                                    return Error(Loc.Dic.error_expenses_create_error);
                            }
                            else
                            {
                                return Error(Loc.Dic.error_invalid_form);
                            }
                        }
                        else
                        {
                            return Error(Loc.Dic.error_no_permission);
                        }
                    }
                    else
                    {
                        return Error(Loc.Dic.error_database_error);
                    }
                }
                else
                {
                    return Error(ModelState);
                }
            }
            else
            {
                return Error(Loc.Dic.error_no_permission);
            }
        }
        public ActionResult Edit(Budgets_Expenses budgets_expenses)
        {
            return Error(Loc.Dic.Error_NoPermission);
            if (Authorized(RoleType.SystemManager))
            {
                if (ModelState.IsValid)
                {
                    Budgets_Expenses expenseFromDB;
                    Budget budget;
                    Projects_ParentProject project;
                    Projects_SubProject subProject;

                    using (BudgetsExpensesRepository expensesRep = new BudgetsExpensesRepository())
                    using (BudgetsRepository budgetRep = new BudgetsRepository(CurrentUser.CompanyId))
                    using (ParentProjectsRepository projectsRep = new ParentProjectsRepository())
                    using (SubProjectsRepository subProjectsRep = new SubProjectsRepository())
                    {
                        expenseFromDB = expensesRep.GetEntity(budgets_expenses.Id);

                        budget = budgetRep.GetEntity(budgets_expenses.BudgetId);
                        project = projectsRep.GetEntity(budgets_expenses.ParentProjectId.Value);
                        subProject = subProjectsRep.GetEntity(budgets_expenses.SubProjectId.Value);

                        if (expenseFromDB != null)
                        {
                            if (budget != null && project != null && subProject != null)
                            {
                                if (budget.CompanyId == CurrentUser.CompanyId && project.CompanyId == CurrentUser.CompanyId && subProject.CompanyId == CurrentUser.CompanyId)
                                {
                                    if (project.IsActive && subProject.IsActive)
                                    {
                                        if (budgets_expenses.Amount < expenseFromDB.Amount)
                                        {
                                            decimal? allocatedToExpense;
                                            using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                                            {
                                                allocatedToExpense = allocationsRep.GetList()
                                                    .Where(x => x.ExpenseId == expenseFromDB.Id)
                                                    .Sum(allocation => (decimal?)allocation.CompanyId); //.Sum(allocation => (decimal?)allocation.Amount);
                                            }

                                            if (allocatedToExpense.HasValue && allocatedToExpense > budgets_expenses.Amount)
                                                return Error(Loc.Dic.error_expenses_allocations_exeeds_amount);
                                        }

                                        expenseFromDB.BudgetId = budgets_expenses.BudgetId;
                                        expenseFromDB.ParentProjectId = budgets_expenses.ParentProjectId;
                                        expenseFromDB.SubProjectId = budgets_expenses.SubProjectId;
                                        expenseFromDB.Amount = budgets_expenses.Amount;
                                        expenseFromDB.CustomName = budgets_expenses.CustomName;

                                        Budgets_Expenses update = expensesRep.Update(expenseFromDB);

                                        if (update != null)
                                            return RedirectToAction("Index");
                                        else
                                            return Error(Loc.Dic.error_expenses_create_error);
                                    }
                                    else
                                    {
                                        return Error(Loc.Dic.error_invalid_form);
                                    }
                                }
                                else
                                {
                                    return Error(Loc.Dic.error_no_permission);
                                }
                            }
                            else
                            {
                                return Error(Loc.Dic.error_database_error);
                            }
                        }
                        else
                        {
                            return Error(Loc.Dic.error_expenses_get_error);
                        }
                    }
                }
                else
                {
                    return Error(ModelState);
                }
            }
            else
            {
                return Error(Loc.Dic.error_no_permission);
            }
        }
        public ActionResult Edit(int id = 0)
        {
            return Error(Loc.Dic.Error_NoPermission);
            if (Authorized(RoleType.SystemManager))
            {
                Budgets_Expenses expense;

                using (BudgetsExpensesRepository expensesRep = new BudgetsExpensesRepository())
                using (BudgetsRepository budgetRep = new BudgetsRepository(CurrentUser.CompanyId))
                using (ParentProjectsRepository projectsRep = new ParentProjectsRepository())
                using (SubProjectsRepository subProjectsRep = new SubProjectsRepository())
                {
                    expense = expensesRep.GetEntity(id);

                    if (expense != null)
                    {
                        if (expense.CompanyId == CurrentUser.CompanyId)
                        {
                            List<SelectListItemDB> budgetsList;
                            List<SelectListItemDB> projectsList;
                            List<SelectListItemDB> subProjectsList;

                            try
                            {
                                budgetsList = budgetRep.GetList()
                                    .Where(budget => budget.CompanyId == CurrentUser.CompanyId && budget.Year >= (DateTime.Now.Year - 1))
                                    .Select(a => new { Id = a.Id, Name = a.Year })
                                    .AsEnumerable()
                                    .Select(x => new SelectListItemDB() { Id = x.Id, Name = x.Name.ToString() })
                                    .ToList();

                                projectsList = projectsRep.GetList()
                                    .Where(type => type.CompanyId == CurrentUser.CompanyId)
                                    .Select(x => new SelectListItemDB() { Id = x.Id, Name = x.Name })
                                    .ToList();

                                subProjectsList = subProjectsRep.GetList()
                                   .Where(type => type.CompanyId == CurrentUser.CompanyId)
                                   .Select(x => new SelectListItemDB() { Id = x.Id, Name = x.Name })
                                   .ToList();
                            }
                            catch
                            {
                                return Error(Loc.Dic.error_database_error);
                            }

                            ViewBag.BudgetId = new SelectList(budgetsList, "Id", "Name", expense.BudgetId);
                            ViewBag.ParentProjectId = new SelectList(projectsList, "Id", "Name", expense.ParentProjectId);
                            ViewBag.SubProjectId = new SelectList(subProjectsList, "Id", "Name", expense.SubProjectId);

                            return View(expense);
                        }
                        else
                        {
                            return Error(Loc.Dic.error_no_permission);
                        }
                    }
                    else
                    {
                        return Error(Loc.Dic.error_income_get_error);
                    }
                }
            }
            else
            {
                return Error(Loc.Dic.error_no_permission);
            }
        }
Exemple #44
0
        public ActionResult Create()
        {
            if (!Authorized(RoleType.OrdersWriter)) return Error(Loc.Dic.error_no_permission);

            using (SuppliersRepository suppliersRep = new SuppliersRepository(CurrentUser.CompanyId))
            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
            using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
            {
                List<Supplier> allSuppliers = suppliersRep.GetList().Where(x => x.ExternalId != null).OrderBy(s => s.Name).ToList();
                if (!allSuppliers.Any()) return Error(Loc.Dic.error_no_suppliers_for_order);

                ViewBag.SupplierId = new SelectList(allSuppliers, "Id", "Name");

                Budget activeBudget = budgetsRep.GetList().SingleOrDefault(x => x.IsActive);
                if (activeBudget == null) return Error(Loc.Dic.error_no_active_budget);

                ViewBag.Allocations = allocationsRep.GetUserAllocations(CurrentUser.UserId, activeBudget.Id);
                if (!((List<Budgets_Allocations>)ViewBag.Allocations).Any()) return Error(Loc.Dic.error_user_have_no_allocations);
                ViewBag.BudgetYear = activeBudget.Year;
                return View();
            }
        }
        public ActionResult Import(int? id)
        {
            if (!Authorized(RoleType.SystemManager)) return Error(Loc.Dic.error_no_permission);
            if (!id.HasValue)
                return View();

            using (BudgetsRepository budgetsRepository = new BudgetsRepository(CurrentUser.CompanyId))
                ViewBag.Year = budgetsRepository.GetEntity(id.Value).Year;

            return View(id);
        }
Exemple #46
0
        public ActionResult Edit(int id = 0)
        {
            if (!Authorized(RoleType.OrdersWriter)) return Error(Loc.Dic.error_no_permission);

            CreateOrderModel model = new CreateOrderModel();
            using (OrdersRepository orderRep = new OrdersRepository(CurrentUser.CompanyId))
            using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
            {
                model.Order = orderRep.GetEntity(id, "Supplier", "Orders_OrderToItem", "Orders_OrderToItem.Orders_Items", "Orders_OrderToAllocation.Budgets_Allocations");
                if (model.Order == null) return Error(Loc.Dic.error_order_not_found);
                if (model.Order.UserId != CurrentUser.UserId) return Error(Loc.Dic.error_no_permission);

                Budget activeBudget = budgetsRep.GetList().SingleOrDefault(x => x.CompanyId == CurrentUser.CompanyId && x.IsActive);
                if (activeBudget == null) return Error(Loc.Dic.error_no_active_budget);

                model.IsFutureOrder = model.Order.IsFutureOrder;

                List<Budgets_Allocations> userAllocations = allocationsRep.GetUserAllocations(CurrentUser.UserId, activeBudget.Id, id);
                if (!userAllocations.Any()) return Error(Loc.Dic.error_user_have_no_allocations);

                model.Allocations = new List<OrderAllocation>();
                List<Orders_OrderToAllocation> validOrderAllocations = model.Order.Orders_OrderToAllocation.ToList();

                var distinctAllocationIds = validOrderAllocations.Select(x => x.AllocationId).Distinct().ToList();
                foreach (var allocationId in distinctAllocationIds)
                {
                    var combineSplitted = validOrderAllocations.Where(x => x.MonthId <= model.Order.CreationDate.Month && x.AllocationId == allocationId);
                    model.Allocations.Add(
                        new OrderAllocation()
                            {
                                AllocationId = allocationId,
                                Name = validOrderAllocations.First(x => x.AllocationId == allocationId).Budgets_Allocations.DisplayName,
                                MonthId = model.Order.CreationDate.Month,
                                IsActive = true,
                                Amount = combineSplitted.Sum(x => x.Amount)
                            }
                    );

                    validOrderAllocations.RemoveAll(x => x.MonthId <= model.Order.CreationDate.Month && x.AllocationId == allocationId);
                }

                foreach (var allocation in validOrderAllocations)
                {
                    model.Allocations.Add(
                        new OrderAllocation()
                        {
                            AllocationId = allocation.AllocationId,
                            Name = allocation.Budgets_Allocations.Name,
                            MonthId = allocation.MonthId,
                            IsActive = true,
                            Amount = allocation.Amount
                        }
                    );
                }

                ViewBag.Allocations = userAllocations;

                int allAllocationsCount = model.Allocations.Count;
                model.Allocations = model.Allocations.Where(x => userAllocations.Any(a => a.Id == x.AllocationId)).ToList();
                int validAllocationsCount = model.Allocations.Count;

                ViewBag.ReAllocationRequired = allAllocationsCount > validAllocationsCount;
                ViewBag.BudgetYear = activeBudget.Year;
                ViewBag.ExistingItems = ItemsToString(model.Order.Orders_OrderToItem);
                return View(model);
            }
        }
        public ActionResult Export(int id = 0)
        {
            if (Authorized(RoleType.SystemManager))
            {
                Budget budgetFromDb;
                List<Budgets_Allocations> allocations = new List<Budgets_Allocations>();

                using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
                {
                    budgetFromDb = budgetsRep.GetEntity(id, "Budgets_Allocations.Budgets_AllocationToMonth");

                    if (budgetFromDb != null)
                    {
                        allocations = budgetFromDb.Budgets_Allocations.ToList();
                    }
                }

                if (allocations != null)
                {
                    StringBuilder builder = new StringBuilder();

                    foreach (var allocation in allocations)
                    {
                        for (int monthNumber = 1; monthNumber <= 12; monthNumber++)
                        {
                            var allocationMonth = allocation.Budgets_AllocationToMonth.SingleOrDefault(x => x.MonthId == monthNumber);
                            decimal monthAmount = allocationMonth == null ? 0 : allocationMonth.Amount;

                            builder.Append(String.Format("{0} ", monthAmount));
                        }

                        builder.AppendLine();
                    }

                    return File(Encoding.UTF8.GetBytes(builder.ToString()),
                     "text/plain",
                      string.Format("{0} - Budget {1}.txt", CurrentUser.CompanyName, budgetFromDb.Year));
                }
                else
                {
                    return Error(Loc.Dic.error_database_error);
                }
            }
            else
            {
                return Error(Loc.Dic.error_no_permission);
            }
        }
Exemple #48
0
 public BudgetsService(BudgetsRepository repo)
 {
     _repo = repo;
 }
        public ActionResult Details(int id = 0)
        {
            if (Authorized(RoleType.SystemManager))
            {
                Budget budget;
                using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
                {
                    budget = budgetsRep.GetEntity(id, "Company");
                }

                if (budget != null)
                {
                    if (budget.CompanyId == CurrentUser.CompanyId)
                    {
                        return View(budget);
                    }
                    else
                    {
                        return Error(Loc.Dic.error_no_permission);
                    }
                }
                else
                {
                    return Error(Loc.Dic.error_budgets_get_error);
                }
            }
            else
            {
                return Error(Loc.Dic.error_no_permission);
            }
        }
        public ActionResult Index()
        {
            if (Authorized(RoleType.SystemManager))
            {
                List<Budgets_Allocations> model;
                List<SelectListItemDB> budgetsList;

                using (BudgetsRepository budgetRep = new BudgetsRepository(CurrentUser.CompanyId))
                using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                {
                    model = allocationsRep.GetList("Budgets_Expenses", "Budgets_Incomes").Where(x => x.CompanyId == CurrentUser.CompanyId).ToList();

                    budgetsList = budgetRep.GetList()
                        .Where(budget => budget.CompanyId == CurrentUser.CompanyId && budget.Year >= (DateTime.Now.Year - 1))
                        .Select(a => new { Id = a.Id, Name = a.Year })
                        .AsEnumerable()
                        .Select(x => new SelectListItemDB() { Id = x.Id, Name = x.Name.ToString() })
                        .ToList();
                }

                ViewBag.BudgetId = new SelectList(budgetsList, "Id", "Name");
                return View(model);
            }
            else
            {
                return Error(Loc.Dic.error_no_permission);
            }
        }
        public ActionResult DeleteConfirmed(int id)
        {
            if (!Authorized(RoleType.SystemManager)) return Error(Loc.Dic.error_no_permission);

            Budget budget;
            List<Budgets_Allocations> budgetAllocations;

            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
            using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
            {
                budget = budgetsRep.GetEntity(id);

                if (budget == null) return Error(Loc.Dic.error_database_error);
                if (budget.CompanyId != CurrentUser.CompanyId) return Error(Loc.Dic.error_no_permission);

                budgetAllocations = budget.Budgets_Allocations.ToList();

                bool isTrueDelete = true;

                if (budgetAllocations.Any())
                {
                    foreach (var allocation in budgetAllocations)
                    {
                        if (
                            allocation.Budgets_BasketsToAllocation.Any() ||
                            allocation.Orders_OrderToAllocation.Any()
                            )
                        {
                            isTrueDelete = false;
                            break;
                        }
                    }
                }

                bool wasDeleted;
                if (isTrueDelete)
                {
                    wasDeleted = budgetsRep.Delete(id);
                }
                else
                {
                    budget.IsCanceled = false;
                    wasDeleted = budgetsRep.Update(budget) != null;
                }

                if (wasDeleted)
                    return RedirectToAction("Index");
                else
                    return Error(Loc.Dic.error_budget_delete_error);
            }
        }
        public ActionResult Edit(Budgets_Allocations Budgets_Allocations)
        {
            return(Error(Loc.Dic.error_no_permission));

            if (Authorized(RoleType.SystemManager))
            {
                if (ModelState.IsValid)
                {
                    Budgets_Allocations allocation;
                    Budgets_Incomes     income;
                    Budgets_Expenses    expense;

                    using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
                        using (BudgetsIncomesRepository incomesRep = new BudgetsIncomesRepository())
                            using (BudgetsExpensesRepository expensesRep = new BudgetsExpensesRepository())
                                using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                                    using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId))
                                    {
                                        allocation = allocationsRep.GetEntity(Budgets_Allocations.Id);

                                        if (allocation != null)
                                        {
                                            if (allocation.CompanyId == CurrentUser.CompanyId)
                                            {
                                                income  = incomesRep.GetEntity(Budgets_Allocations.IncomeId.Value);
                                                expense = expensesRep.GetEntity(Budgets_Allocations.ExpenseId.Value);

                                                if (income != null && expense != null)
                                                {
                                                    if (income.BudgetId == allocation.BudgetId && expense.BudgetId == allocation.BudgetId)
                                                    {
                                                        decimal?totalUsed;
                                                        decimal?allocatedToExpense;
                                                        decimal?allocatedToIncome;

                                                        totalUsed = 0; //totalUsed = ordersRep.GetList()
                                                        //    .Where(order => order.BudgetAllocationId == Budgets_Allocations.Id && order.StatusId >= (int)StatusType.ApprovedPendingInvoice)
                                                        //    .Sum(x => (decimal?)x.Price);

                                                        if ((totalUsed ?? 0) > Budgets_Allocations.CompanyId)//if ((totalUsed ?? 0) > Budgets_Allocations.Amount)
                                                        {
                                                            return(Error(Loc.Dic.error_allocations_amount_is_used));
                                                        }

                                                        allocatedToIncome = allocationsRep.GetList()
                                                                            .Where(x => x.IncomeId == income.Id && x.Id != Budgets_Allocations.Id)
                                                                            .Sum(alloc => (decimal?)alloc.CompanyId);                 //.Sum(alloc => (decimal?)alloc.Amount);

                                                        if ((allocatedToIncome ?? 0) + Budgets_Allocations.CompanyId > income.Amount) //if ((allocatedToIncome ?? 0) + Budgets_Allocations.Amount > income.Amount)
                                                        {
                                                            return(Error(Loc.Dic.error_income_full_allocation));
                                                        }

                                                        allocatedToExpense = allocationsRep.GetList()
                                                                             .Where(x => x.ExpenseId == expense.Id && x.Id != Budgets_Allocations.Id)
                                                                             .Sum(alloc => (decimal?)alloc.CompanyId);                  //.Sum(alloc => (decimal?)alloc.Amount);

                                                        if ((allocatedToExpense ?? 0) + Budgets_Allocations.CompanyId > expense.Amount) //if ((allocatedToExpense ?? 0) + Budgets_Allocations.Amount > expense.Amount)
                                                        {
                                                            return(Error(Loc.Dic.error_expenses_full_allocation));
                                                        }

                                                        allocation.IncomeId  = Budgets_Allocations.IncomeId;
                                                        allocation.ExpenseId = Budgets_Allocations.ExpenseId;
                                                        allocation.CompanyId = Budgets_Allocations.CompanyId;//allocation.Amount = Budgets_Allocations.Amount;

                                                        Budgets_Allocations update = allocationsRep.Update(allocation);

                                                        if (update != null)
                                                        {
                                                            return(RedirectToAction("Index"));
                                                        }
                                                        else
                                                        {
                                                            return(Error(Loc.Dic.error_allocations_get_error));
                                                        }
                                                    }
                                                    else
                                                    {
                                                        return(Error(Loc.Dic.error_invalid_form));
                                                    }
                                                }
                                                else
                                                {
                                                    return(Error(Loc.Dic.error_database_error));
                                                }
                                            }
                                            else
                                            {
                                                return(Error(Loc.Dic.error_no_permission));
                                            }
                                        }
                                        else
                                        {
                                            return(Error(Loc.Dic.error_allocations_get_error));
                                        }
                                    }
                }
                else
                {
                    return(Error(ModelState));
                }
            }
            else
            {
                return(Error(Loc.Dic.error_no_permission));
            }
        }
        public ActionResult Create(Budget budget)
        {
            if (Authorized(RoleType.SystemManager))
            {
                if (ModelState.IsValid)
                {
                    if (budget.Year >= DateTime.Now.Year)
                    {
                        budget.CompanyId = CurrentUser.CompanyId;
                        budget.IsActive = false;

                        bool wasCreated;
                        using (BudgetsRepository budgetRep = new BudgetsRepository(CurrentUser.CompanyId))
                        {
                            bool yearExists = budgetRep.GetList().Any(x => x.CompanyId == CurrentUser.CompanyId && x.Year == budget.Year);

                            if (yearExists)
                                return Error(Loc.Dic.error_budgets_year_exists);

                            wasCreated = budgetRep.Create(budget);
                        }

                        if (wasCreated)
                            return RedirectToAction("Index");
                        else
                            return Error(Loc.Dic.error_budgets_create_error);
                    }
                    else
                    {
                        return Error(Loc.Dic.error_budgets_year_passed);
                    }
                }
                else
                {
                    return Error(ModelState);
                }
            }
            else
            {
                return Error(Loc.Dic.error_no_permission);
            }
        }
        public ActionResult DeleteConfirmed(int id)
        {
            if (!Authorized(RoleType.SystemManager))
            {
                return(Error(Loc.Dic.error_no_permission));
            }

            Budget budget;
            List <Budgets_Allocations> budgetAllocations;

            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
                using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                {
                    budget = budgetsRep.GetEntity(id);

                    if (budget == null)
                    {
                        return(Error(Loc.Dic.error_database_error));
                    }
                    if (budget.CompanyId != CurrentUser.CompanyId)
                    {
                        return(Error(Loc.Dic.error_no_permission));
                    }

                    budgetAllocations = budget.Budgets_Allocations.ToList();

                    bool isTrueDelete = true;

                    if (budgetAllocations.Any())
                    {
                        foreach (var allocation in budgetAllocations)
                        {
                            if (
                                allocation.Budgets_BasketsToAllocation.Any() ||
                                allocation.Orders_OrderToAllocation.Any()
                                )
                            {
                                isTrueDelete = false;
                                break;
                            }
                        }
                    }

                    bool wasDeleted;
                    if (isTrueDelete)
                    {
                        wasDeleted = budgetsRep.Delete(id);
                    }
                    else
                    {
                        budget.IsCanceled = false;
                        wasDeleted        = budgetsRep.Update(budget) != null;
                    }

                    if (wasDeleted)
                    {
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        return(Error(Loc.Dic.error_budget_delete_error));
                    }
                }
        }
        public ActionResult EditAllocations(int id = 0, int budgetId = 0)
        {
            if (!Authorized(RoleType.SystemManager))
                return Error(Loc.Dic.error_no_permission);

            PermissionAllocationsModel model = new PermissionAllocationsModel();
            Budget budget;

            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
            using (BudgetsPermissionsRepository permissionsRep = new BudgetsPermissionsRepository())
            using (BasketsToAllocationsRepository permissionsAllocationsRep = new BasketsToAllocationsRepository())
            {
                model.Basket = permissionsRep.GetEntity(id);

                if (model.Basket == null)
                    return Error(Loc.Dic.error_permissions_get_error);

                if (model.Basket.CompanyId != CurrentUser.CompanyId)
                    return Error(Loc.Dic.error_no_permission);

                budget = budgetsRep.GetEntity(budgetId);

                if (budget == null)
                    return Error(Loc.Dic.error_database_error);

                List<PermissionAllocation> permissionsToAllocations = permissionsAllocationsRep.GetList("Budgets_Allocations", "Budgets_Allocations.Budgets_Incomes", "Budgets_Allocations.Budgets_Expenses")
                    .Where(x => x.BudgetId == budget.Id && x.BasketId == model.Basket.Id)
                    .AsEnumerable()
                    .Select(alloc => new PermissionAllocation() { IsActive = true, Allocation = alloc })
                    .ToList();

                model.BudgetAllocations = new BudgetAllocations()
                {
                    Budget = budget,
                    AllocationsList = budget.Budgets_Allocations.OrderBy(x=>x.SortingCode).ToList(),
                    PermissionAllocations = permissionsToAllocations
                };

                return View(model);
            }
        }
        public ActionResult EditAllocations(PermissionAllocationsModel model)
        {
            if (!Authorized(RoleType.SystemManager))
                return Error(Loc.Dic.error_no_permission);

            Budgets_Baskets permissionFromDB;
            List<Budgets_Allocations> existingPermissionAllocations;
            List<Budgets_BasketsToAllocation> existingPermissionToAllocations;

            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
            using (BudgetsPermissionsRepository permissionsRep = new BudgetsPermissionsRepository())
            using (BasketsToAllocationsRepository permissionsAllocationsRep = new BasketsToAllocationsRepository())
            using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
            {
                permissionFromDB = permissionsRep.GetEntity(model.Basket.Id);
                //TODO: Error gets ALL pemissions from DB
                existingPermissionAllocations = permissionsAllocationsRep.GetList().Where(x => x.BasketId == permissionFromDB.Id).Select(y => y.Budgets_Allocations).ToList();
                existingPermissionToAllocations = permissionsAllocationsRep.GetList().Where(x => x.BasketId == permissionFromDB.Id).ToList();

                if (permissionFromDB == null)
                    return Error(Loc.Dic.error_database_error);

                if (permissionFromDB.CompanyId != CurrentUser.CompanyId)
                    return Error(Loc.Dic.error_no_permission);

                Budget budgetFromDB = budgetsRep.GetEntity(model.BudgetAllocations.Budget.Id);

                if (budgetFromDB == null)
                    return Error(Loc.Dic.error_database_error);

                if (budgetFromDB.CompanyId != CurrentUser.CompanyId)
                    return Error(Loc.Dic.error_no_permission);

                foreach (var allocation in model.BudgetAllocations.PermissionAllocations)
                {
                    if (allocation.IsActive)
                    {
                        if (!existingPermissionAllocations.Any(x => x.Id == allocation.Allocation.BudgetsAllocationId))
                        {
                            allocation.Allocation.BudgetId = budgetFromDB.Id;
                            allocation.Allocation.BasketId = permissionFromDB.Id;
                            if(!permissionsAllocationsRep.Create(allocation.Allocation)) return Error(Loc.Dic.error_database_error);
                        }
                    }
                    else
                    {
                        if (existingPermissionAllocations.Any(x => x.Id == allocation.Allocation.BudgetsAllocationId))
                        {
                            permissionsAllocationsRep.Delete(allocation.Allocation.Id);
                        }
                    }
                }

                return RedirectToAction("BudgetBaskets", new { id = budgetFromDB.Id });
            }
        }
        public ActionResult Create(Budgets_Allocations Budgets_Allocations, int id = 0)
        {
            return Error(Loc.Dic.error_no_permission);
            if (Authorized(RoleType.SystemManager))
            {
                if (ModelState.IsValid)
                {
                    Budget budget;
                    Budgets_Incomes income;
                    Budgets_Expenses expense;

                    using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
                    using (BudgetsIncomesRepository incomesRep = new BudgetsIncomesRepository())
                    using (BudgetsExpensesRepository expensesRep = new BudgetsExpensesRepository())
                    using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                    {
                        budget = budgetsRep.GetEntity(id);

                        if (budget != null)
                        {
                            if (budget.CompanyId == CurrentUser.CompanyId)
                            {

                                income = incomesRep.GetEntity(Budgets_Allocations.IncomeId.Value);
                                expense = expensesRep.GetEntity(Budgets_Allocations.ExpenseId.Value);

                                if (income != null && expense != null)
                                {
                                    if (income.BudgetId == budget.Id && expense.BudgetId == budget.Id)
                                    {
                                        decimal? allocatedToExpense;
                                        decimal? allocatedToIncome;

                                        allocatedToIncome = allocationsRep.GetList()
                                             .Where(x => x.IncomeId == income.Id)
                                             .Sum(allocation => (decimal?)allocation.CompanyId);//.Sum(allocation => (decimal?)allocation.Amount);

                                        if ((allocatedToIncome ?? 0) + Budgets_Allocations.CompanyId > income.Amount)//if ((allocatedToIncome ?? 0) + Budgets_Allocations.Amount > income.Amount)
                                            return Error(Loc.Dic.error_income_full_allocation);

                                        allocatedToExpense = allocationsRep.GetList()
                                            .Where(x => x.ExpenseId == expense.Id)
                                            .Sum(allocation => (decimal?)allocation.CompanyId);//.Sum(allocation => (decimal?)allocation.Amount);

                                        if ((allocatedToExpense ?? 0) + Budgets_Allocations.CompanyId > expense.Amount)//if ((allocatedToExpense ?? 0) + Budgets_Allocations.Amount > expense.Amount)
                                            return Error(Loc.Dic.error_expenses_full_allocation);

                                        Budgets_Allocations.CompanyId = CurrentUser.CompanyId;
                                        Budgets_Allocations.BudgetId = budget.Id;
                                        Budgets_Allocations.CompanyId = CurrentUser.CompanyId;

                                        if (allocationsRep.Create(Budgets_Allocations))
                                            return RedirectToAction("Index");
                                        else
                                            return Error(Loc.Dic.error_database_error);
                                    }
                                    else
                                    {
                                        return Error(Loc.Dic.error_invalid_form);
                                    }
                                }
                                else
                                {
                                    return Error(Loc.Dic.error_database_error);

                                }
                            }
                            else
                            {
                                return Error(Loc.Dic.error_no_permission);
                            }
                        }
                        else
                        {
                            return Error(Loc.Dic.error_database_error);
                        }
                    }
                }
                else
                {
                    return Error(ModelState);
                }
            }
            else
            {
                return Error(Loc.Dic.error_no_permission);
            }
        }