Exemplo n.º 1
0
        public void AllocationRepository_Delete_ShouldBeOk()
        {
            Allocation allocation = ObjectMother.GetAllocation(ObjectMother.GetEmployee(), ObjectMother.GetRoom());

            allocation.Id = 2;

            _repository.Delete(allocation);
            Allocation deleteObject = _repository.Get(2);

            deleteObject.Should().BeNull();
        }
        public ActionResult DeleteConfirmed(int id)
        {
            return(Error(Loc.Dic.error_no_permission));

            if (Authorized(RoleType.SystemManager))
            {
                Budgets_Allocations allocation;
                using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId))
                    using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                        using (BasketsToAllocationsRepository allocationsPermissionsRep = new BasketsToAllocationsRepository())
                        {
                            allocation = allocationsRep.GetEntity(id, "Budgets_Incomes", "Budgets_Expenses");

                            if (allocation != null)
                            {
                                if (allocation.CompanyId == CurrentUser.CompanyId)
                                {
                                    if (false) //if (allocation.Orders.All(x => x.StatusId < (int)StatusType.ApprovedPendingInvoice))
                                    {
                                        bool         noErrors         = true;
                                        List <Order> allocationOrders = new List <Order>();//List<Order> allocationOrders = allocation.Orders.ToList();

                                        foreach (var item in allocationOrders)
                                        {
                                            item.StatusId             = (int)StatusType.Declined;
                                            item.LastStatusChangeDate = DateTime.Now;

                                            //item.OrderApproverNotes = YOUR_ALLOCATION_WAS_REVOKED;
                                            item.NextOrderApproverId = null;

                                            if (ordersRep.Update(item) == null)
                                            {
                                                noErrors = false;
                                            }
                                        }

                                        List <int> allocationPermission = allocation.Budgets_BasketsToAllocation.Select(x => x.Id).ToList();
                                        foreach (var itemId in allocationPermission)
                                        {
                                            if (!allocationsPermissionsRep.Delete(itemId))
                                            {
                                                noErrors = false;
                                            }
                                        }

                                        if (!allocationsRep.Delete(allocation.Id))
                                        {
                                            noErrors = false;
                                        }

                                        if (noErrors)
                                        {
                                            return(RedirectToAction("Index"));
                                        }
                                        else
                                        {
                                            return(Error(Loc.Dic.error_allocations_delete_error));
                                        }
                                    }
                                    else
                                    {
                                        return(Error(Loc.Dic.error_allocations_has_approved_orders));
                                    }
                                }
                                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));
            }
        }
Exemplo n.º 3
0
        public ActionResult DeleteConfirmed(int id)
        {
            return(Error(Loc.Dic.Error_NoPermission));

            if (Authorized(RoleType.SystemManager))
            {
                Budgets_Incomes income;
                using (BudgetsIncomesRepository incomesRep = new BudgetsIncomesRepository())
                    using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId))
                        using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                            using (BasketsToAllocationsRepository permissionAllocationsRep = new BasketsToAllocationsRepository())
                            {
                                income = incomesRep.GetEntity(id, "Budget", "Budgets_Incomes_types", "Budgets_Incomes_Institutions");

                                if (income != null)
                                {
                                    if (income.CompanyId == CurrentUser.CompanyId)
                                    {
                                        List <Budgets_Allocations>         incomeAllocations;
                                        List <Budgets_BasketsToAllocation> incomePermissions;
                                        List <Order> incomeOrders = ordersRep.GetList().Where(x => x.CompanyId == income.Id).ToList(); //List<Order> incomeOrders = ordersRep.GetList().Where(x => x.Budgets_Allocations.IncomeId == income.Id).ToList();

                                        if (!incomeOrders.Any(o => o.StatusId >= (int)StatusType.ApprovedPendingInvoice))
                                        {
                                            try
                                            {
                                                incomeAllocations = allocationsRep.GetList().Where(x => x.IncomeId == income.Id).ToList();
                                                incomePermissions = permissionAllocationsRep.GetList().Where(x => x.Budgets_Allocations.IncomeId == income.Id).ToList();

                                                foreach (var item in incomeOrders)
                                                {
                                                    ordersRep.Delete(item.Id);
                                                }

                                                foreach (var item in incomePermissions)
                                                {
                                                    permissionAllocationsRep.Delete(item.Id);
                                                }

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

                                                incomesRep.Delete(income.Id);
                                            }
                                            catch
                                            {
                                                return(Error(Loc.Dic.error_database_error));
                                            }

                                            return(RedirectToAction("Index"));
                                        }
                                        else
                                        {
                                            return(Error(Loc.Dic.error_income_delete_has_approved_orders));
                                        }
                                    }
                                    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));
            }
        }
Exemplo n.º 4
0
        public ActionResult DeleteConfirmed(int id)
        {
            return Error(Loc.Dic.Error_NoPermission);
            if (Authorized(RoleType.SystemManager))
            {
                Budgets_Expenses expense;
                using (BudgetsExpensesRepository expensesRep = new BudgetsExpensesRepository())
                using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId))
                using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                using (BasketsToAllocationsRepository permissionAllocationsRep = new BasketsToAllocationsRepository())
                {
                    expense = expensesRep.GetEntity(id, "Budget", "Budgets_Incomes_types", "Budgets_Incomes_Institutions");

                    if (expense != null)
                    {
                        if (expense.CompanyId == CurrentUser.CompanyId)
                        {
                            List<Budgets_Allocations> expenseAllocations;
                            List<Budgets_BasketsToAllocation> expensePermissions;
                            List<Order> expenseOrders = ordersRep.GetList().Where(x => x.CompanyId == expense.Id).ToList(); //List<Order> expenseOrders = ordersRep.GetList().Where(x => x.Budgets_Allocations.ExpenseId == expense.Id).ToList();

                            if (!expenseOrders.Any(o => o.StatusId >= (int)StatusType.ApprovedPendingInvoice))
                            {
                                try
                                {
                                    expenseAllocations = allocationsRep.GetList().Where(x => x.ExpenseId == expense.Id).ToList();
                                    expensePermissions = permissionAllocationsRep.GetList().Where(x => x.Budgets_Allocations.ExpenseId == expense.Id).ToList();

                                    foreach (var item in expenseOrders)
                                    {
                                        ordersRep.Delete(item.Id);
                                    }

                                    foreach (var item in expensePermissions)
                                    {
                                        permissionAllocationsRep.Delete(item.Id);
                                    }

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

                                    expensesRep.Delete(expense.Id);
                                }
                                catch
                                {
                                    return Error(Loc.Dic.error_database_error);
                                }

                                return RedirectToAction("Index");
                            }
                            else
                            {
                                return Error(Loc.Dic.error_expenses_delete_has_approved_orders);
                            }
                        }
                        else
                        {
                            return Error(Loc.Dic.error_no_permission);
                        }
                    }
                    else
                    {
                        return Error(Loc.Dic.error_expenses_get_error);
                    }
                }
            }
            else
            {
                return Error(Loc.Dic.error_no_permission);
            }
        }
Exemplo n.º 5
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");
        }
Exemplo n.º 6
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";
        }
        public ActionResult DeleteConfirmed(int id)
        {
            return Error(Loc.Dic.error_no_permission);
            if (Authorized(RoleType.SystemManager))
            {
                Budgets_Allocations allocation;
                using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId))
                using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                using (BasketsToAllocationsRepository allocationsPermissionsRep = new BasketsToAllocationsRepository())
                {
                    allocation = allocationsRep.GetEntity(id, "Budgets_Incomes", "Budgets_Expenses");

                    if (allocation != null)
                    {
                        if (allocation.CompanyId == CurrentUser.CompanyId)
                        {
                            if (false) //if (allocation.Orders.All(x => x.StatusId < (int)StatusType.ApprovedPendingInvoice))
                            {
                                bool noErrors = true;
                                List<Order> allocationOrders = new List<Order>();//List<Order> allocationOrders = allocation.Orders.ToList();

                                foreach (var item in allocationOrders)
                                {
                                    item.StatusId = (int)StatusType.Declined;
                                    item.LastStatusChangeDate = DateTime.Now;

                                    //item.OrderApproverNotes = YOUR_ALLOCATION_WAS_REVOKED;
                                    item.NextOrderApproverId = null;

                                    if (ordersRep.Update(item) == null)
                                        noErrors = false;
                                }

                                List<int> allocationPermission = allocation.Budgets_BasketsToAllocation.Select(x => x.Id).ToList();
                                foreach (var itemId in allocationPermission)
                                {
                                    if (!allocationsPermissionsRep.Delete(itemId))
                                        noErrors = false;
                                }

                                if (!allocationsRep.Delete(allocation.Id))
                                    noErrors = false;

                                if (noErrors)
                                    return RedirectToAction("Index");
                                else
                                    return Error(Loc.Dic.error_allocations_delete_error);
                            }
                            else
                            {
                                return Error(Loc.Dic.error_allocations_has_approved_orders);
                            }
                        }
                        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);
            }
        }