Example #1
0
        public void GivenAnAllocation_WhenStopAllocation_ThenRepoReturnsAllocationWithStatusAndStartTime()
        {
            var allocation = new Allocation()
            {
                Id             = "1111",
                ParkinglotId   = 5,
                MemberPersonId = 1,
            };

            var options = new DbContextOptionsBuilder <ParkSharkContext>()
                          .UseInMemoryDatabase("parkshark" + Guid.NewGuid().ToString("n"))
                          .Options;


            //When
            using (var context = new ParkSharkContext(options))
            {
                context.Add(allocation);
                context.SaveChanges();
                allocation.Status = StatusAllocation.Passive;
                AllocationRepository allocationRepository = new AllocationRepository(context, _personRepository, _parkinglotRepository);
                var result = allocationRepository.UpdateAllocation(allocation);
                //Then
                Assert.Equal("Passive", context.Allocations.SingleOrDefault(al => al.Id == "1111").Status.ToString());
            }
        }
Example #2
0
            public override async Task <AllocationDto> Handle(Command request, CancellationToken cancellationToken)
            {
                var category = await BudgetCategoryRepository.GetByIdAsync(request.TargetBudgetCategoryId);

                if (category == null)
                {
                    throw new NotFoundException("Target budget category was not found.");
                }


                var allocationEntity = Mapper.Map <Domain.Entities.Allocation>(request);

                allocationEntity.CreatedByUserId  = AuthenticationProvider.User.UserId;
                allocationEntity.CreationDateTime = DateTime.Now;

                var savedAllocation = await AllocationRepository.AddAsync(allocationEntity);

                var addedRows = await AllocationRepository.SaveChangesAsync(cancellationToken);

                if (addedRows.IsNullOrDefault())
                {
                    throw new SaveFailureException(nameof(allocationEntity), allocationEntity);
                }

                var dto = Mapper.Map <AllocationDto>(savedAllocation);

                _ = _mediator.Publish(new Notification()
                {
                    BudgetId   = category.BudgetId,
                    Allocation = dto
                }, cancellationToken);
                return(dto);
            }
        private async Task <int> MigrateAllocations()
        {
            List <ProjectAllocation> records    = sqlDataContext.ProjectAllocations.ToList();
            AllocationRepository     repository = new AllocationRepository();
            int recCount = 0;

            try
            {
                // delete all existing records from Postgres Database
                postgressDataContext.ProjectAllocations.RemoveRange(postgressDataContext.ProjectAllocations);
                await postgressDataContext.SaveChangesAsync();

                // Migrage SQL Server data into Postgress database
                foreach (ProjectAllocation rec in records)
                {
                    postgressDataContext.ProjectAllocations.Add(rec);
                }
                await postgressDataContext.SaveChangesAsync();

                //await UpdateAllocations();
                recCount = records.Count;
            }
            catch (Exception exp)
            {
                MessageBox.Show($"Error while migrating Project Allocations. The error is {Environment.NewLine}Main Exception: {exp.Message}{Environment.NewLine}Inner Exception: {exp.InnerException?.Message}");
            }

            return(recCount);
        }
        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 HomeController()
 {
     repository                    = new CommonDataRepositroy();
     concDataRepository            = new ConcDataRepository();
     dataCalculationRepository     = new DataCalculationRepository();
     basicAllocationRepository     = new AllocationRepository();
     basicAllocationDataRepository = new BasicAllocationDataRepository();
 }
 public AllocationsMessengerServiceProcessor()
 {
     allocationService = new AllocationRepository();
     empService        = new EmployeeRepository();
     settingRepository = new SystemSettingRepository();
     logger            = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
     log4net.Config.XmlConfigurator.Configure();
 }
        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));
            }
        }
Example #8
0
        public void GivenAnAllocation_WhenStartAllocation_ThenRepoReturnsAllocationWithStatusAndStartTime()
        {
            //Given

            var name         = "test";
            var mobilePhone  = "000";
            var phone        = "";
            var street       = "street";
            var streetnr     = "01";
            var postalcode   = "1234";
            var city         = "kjhg";
            var licenseplate = "123";
            var country      = "bel";
            var mail         = "*****@*****.**";

            //When
            var newperson = new Person
                            (
                name,
                mobilePhone,
                phone,
                new Address
            {
                CityName     = city,
                PostalCode   = postalcode,
                StreetName   = street,
                StreetNumber = streetnr
            },
                mail,
                new LicensePlate(licenseplate, country)
                            );

            var allocation = new Allocation()
            {
                ParkinglotId   = 5,
                MemberPersonId = 1
            };

            var options = new DbContextOptionsBuilder <ParkSharkContext>()
                          .UseInMemoryDatabase("parkshark" + Guid.NewGuid().ToString("n"))
                          .Options;


            //When
            using (var context = new ParkSharkContext(options))
            {
                AllocationRepository allocationRepository = new AllocationRepository(context, _personRepository, _parkinglotRepository);
                _personRepository.GetById(1).Returns(newperson);
                _parkinglotRepository.GetOneParkinglot(5).Returns(new Parkinglot());
                var result = allocationRepository.SaveNewAllocation(allocation);
                //Then
                Assert.Equal(DateTime.Now.ToString("MM/dd/yyyy"), result.StartingTime.ToString("MM/dd/yyyy"));
                Assert.Equal("Active", result.Status.ToString());
            }
        }
Example #9
0
            public override async Task <AllocationDto> Handle(Query request, CancellationToken cancellationToken)
            {
                var allocationEntity = await AllocationRepository.GetByIdAsync(request.AllocationId);

                if (allocationEntity.IsNullOrDefault() || !await BudgetCategoryRepository.IsAccessibleToUser(allocationEntity.Id))
                {
                    throw new NotFoundException("Target allocation was not found.");
                }

                return(Mapper.Map <AllocationDto>(allocationEntity));
            }
Example #10
0
            public override async Task <IEnumerable <AllocationDto> > Handle(Query request, CancellationToken cancellationToken)
            {
                if (request.Filters == null)
                {
                    request.Filters = new AllocationFilterDto();
                }

                var allocations = await AllocationRepository.ListWithFilter(Mapper.Map <Domain.Entities.Budget>(request.Budget), Mapper.Map <AllocationFilterModel>(request.Filters));

                return(Mapper.Map <IEnumerable <AllocationDto> >(allocations));
            }
Example #11
0
        public Cancelator(IDatabase db)
        {
            ambulanceRepository  = new AmbulanceRepository(db);
            hospitalRepository   = new HospitalRepository(db);
            incidentRepository   = new IncidentRepository(db);
            allocationRepository = new AllocationRepository(db);

            sender = new RabbitMQMessageSender();
            allocationsToProcess = new BlockingCollection <Allocation>();

            new Thread(Start).Start();
        }
Example #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:UCLouvain.AmbulanceSystem.Server.AmbulanceAllocator"/> class.
        /// </summary>
        /// <param name="db">Db. Do not share among threads.</param>
        public TrafficJamReallocator(MapService mapService, IDatabase db)
        {
            ambulanceRepository  = new AmbulanceRepository(db);
            hospitalRepository   = new HospitalRepository(db);
            incidentRepository   = new IncidentRepository(db);
            allocationRepository = new AllocationRepository(db);

            this.mapService         = mapService;
            this.incidentsToProcess = new BlockingCollection <Incident>();

            new Thread(this.Start).Start();
        }
Example #13
0
        public ApiController()
        {
            var provider         = new PostgreSQLDatabaseProvider();
            var connectionString = ConfigurationManager.ConnectionStrings["postgres"].ConnectionString;
            var config           = DatabaseConfiguration.Build()
                                   .UsingConnectionString(connectionString)
                                   .UsingProvider(provider)
                                   .UsingDefaultMapper <ConventionMapper>();
            var db = new Database(config);

            ambulanceRepository  = new AmbulanceRepository(db);
            hospitalRepository   = new HospitalRepository(db);
            incidentRepository   = new IncidentRepository(db);
            allocationRepository = new AllocationRepository(db);
        }
        public AllocationsUpdaterServiceProcessor()
        {
            logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            log4net.Config.XmlConfigurator.Configure();

            allocationRepo     = new AllocationRepository();
            employeeRepo       = new EmployeeRepository();
            projectRepo        = new ProjectRepository();
            trackerRepo        = new NotificationsTrackerRepository();
            practiceRepository = new PracticeRepository();
            settingRepository  = new SystemSettingRepository();

            emailClientIP = ProcessorHelper.GetSettingsValue(ProcessorHelper.EMAIL_PROXY_SERVER);
            ownerEmailID  = ProcessorHelper.GetSettingsValue(ProcessorHelper.CONTRACTOR_REQ_EMAIL_OWNER);
            outlookPwd    = ProcessorHelper.GetSettingsValue(ProcessorHelper.EMAIL_OWNERS_PASSWORD);
        }
        public ActionResult Details(int id = 0)
        {
            if (Authorized(RoleType.SystemManager))
            {
                AllocationDetailsModel model = new AllocationDetailsModel();

                using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                {
                    model.OriginalAllocation  = allocationsRep.GetEntity(id, "Budgets_AllocationToMonth");
                    model.RemainingAllocation = new Budgets_Allocations();

                    List <Orders_OrderToAllocation> approvedAllocations = model.OriginalAllocation.Orders_OrderToAllocation.Where(x => x.Order.StatusId >= (int)StatusType.InvoiceApprovedByOrderCreatorPendingFileExport).ToList();

                    foreach (var month in model.OriginalAllocation.Budgets_AllocationToMonth)
                    {
                        decimal?remainingAmount = month.Amount - approvedAllocations.Where(m => m.MonthId == month.MonthId).Select(d => (decimal?)d.Amount).Sum();

                        model.RemainingAllocation.Budgets_AllocationToMonth.Add(new Budgets_AllocationToMonth()
                        {
                            MonthId = month.MonthId,
                            Amount  = remainingAmount.HasValue ? remainingAmount.Value : 0
                        });
                    }
                }

                if (model.OriginalAllocation != null)
                {
                    if (model.OriginalAllocation.CompanyId == CurrentUser.CompanyId)
                    {
                        return(View(model));
                    }
                    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));
            }
        }
Example #16
0
            public override async Task <AllocationDto> Handle(Command request, CancellationToken cancellationToken)
            {
                var allocation = await AllocationRepository.GetByIdAsync(request.AllocationId);

                if (allocation == null)
                {
                    throw new NotFoundException("Target allocation was not found.");
                }

                var originalTargetCategoryAccessible = await BudgetCategoryRepository.IsAccessibleToUser(allocation.TargetBudgetCategoryId);

                var targetCategoryAccessible = await BudgetCategoryRepository.IsAccessibleToUser(request.TargetBudgetCategoryId);

                if (!targetCategoryAccessible || !originalTargetCategoryAccessible)
                {
                    throw new NotFoundException("Target budget category was not found.");
                }

                if (request.SourceBudgetCategoryId != null)
                {
                    var sourceCategoryAccessible = BudgetCategoryRepository.IsAccessibleToUser(request.SourceBudgetCategoryId.Value);
                    if (!await sourceCategoryAccessible)
                    {
                        throw new NotFoundException("Source budget category was not found.");
                    }
                }

                allocation.Description            = request.Description;
                allocation.AllocationDateTime     = request.AllocationDate;
                allocation.TargetBudgetCategoryId = request.TargetBudgetCategoryId;
                allocation.SourceBudgetCategoryId = request.SourceBudgetCategoryId;
                allocation.Amount = request.Amount;

                await AllocationRepository.UpdateAsync(allocation);

                await AllocationRepository.SaveChangesAsync(cancellationToken);

                var dto = Mapper.Map <AllocationDto>(allocation);

                _ = _mediator.Publish(new Notification()
                {
                    BudgetId   = allocation.TargetBudgetCategory.BudgetId,
                    Allocation = dto
                }, cancellationToken);
                return(dto);
            }
        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);
        }
Example #18
0
            public override async Task <AllocationDto> Handle(Command request, CancellationToken cancellationToken)
            {
                var allocationEntity = await AllocationRepository.GetByIdAsync(request.AllocationId);

                if (allocationEntity.IsNullOrDefault() || !await BudgetCategoryRepository.IsAccessibleToUser(allocationEntity.TargetBudgetCategoryId))
                {
                    throw new NotFoundException("Target allocation was not found.");
                }

                await AllocationRepository.DeleteAsync(allocationEntity);

                await AllocationRepository.SaveChangesAsync(cancellationToken);

                _ = _mediator.Publish(new Notification()
                {
                    BudgetId = allocationEntity.TargetBudgetCategory.BudgetId,
                }, cancellationToken);
                return(Mapper.Map <AllocationDto>(allocationEntity));
            }
        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 Delete(int id = 0)
        {
            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))
                                    {
                                        return(View(allocation));
                                    }
                                    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));
            }
        }
Example #22
0
        public HomeController()
        {
            // var provider = new MonoSQLiteDatabaseProvider();
            var provider         = new PostgreSQLDatabaseProvider();
            var connectionString = ConfigurationManager.ConnectionStrings["postgres"].ConnectionString;
            var config           = DatabaseConfiguration.Build()
                                   .UsingConnectionString(connectionString)
                                   .UsingProvider(provider)
                                   .UsingDefaultMapper <ConventionMapper>();
            var db = new Database(config);

            // connection.Open();

            //logger.Info (db.ExecuteScalar<int>("select count(*) from ambulances where ambulances.ambulanceId = 'A9';"));

            ambulanceRepository  = new AmbulanceRepository(db);
            hospitalRepository   = new HospitalRepository(db);
            incidentRepository   = new IncidentRepository(db);
            allocationRepository = new AllocationRepository(db);
        }
Example #23
0
        public Checker(IDatabaseBuildConfiguration config)
        {
            this.config = config;
            var db = new Database(config);

            ambulanceRepository     = new AmbulanceRepository(db);
            hospitalRepository      = new HospitalRepository(db);
            incidentRepository      = new IncidentRepository(db);
            allocationRepository    = new AllocationRepository(db);
            configurationRepository = new ConfigurationRepository(db);

            mapService = new MapService();

            allocator = new DefaultAmbulanceAllocator(mapService, new LoggedDatabase(config));
            configurationRepository.UpdateActiveAllocator("DefaultAmbulanceAllocator");

            mobilizator           = new AmbulanceMobilizator(new Database(config));
            trafficJamReallocator = new TrafficJamReallocator(mapService, new LoggedDatabase(config));
            cancelator            = new Cancelator(new Database(config));
        }
Example #24
0
        public Orchestrator(IDatabaseBuildConfiguration config)
        {
            var db = new Database(config);

            ambulanceRepository        = new AmbulanceRepository(db);
            ambulanceStationRepository = new AmbulanceStationRepository(db);
            hospitalRepository         = new HospitalRepository(db);
            incidentRepository         = new IncidentRepository(db);
            allocationRepository       = new AllocationRepository(db);

            mapService = new MapService();

            ip = new IncidentProcessor(this);
            //allocator = new AmbulanceAllocator(mapService, new LoggedDatabase(config));
            //mobilizator = new AmbulanceMobilizator(new Database (config));
            //trafficJamReallocator = new TrafficJamReallocator(mapService, new LoggedDatabase(config));
            //cancelator = new Cancelator(new Database(config));

            checker = new Checker(config);
            checker.Start();
        }
        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()));
                }
        }
Example #26
0
        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));
            }
        }
Example #28
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 AllocationController(AllocationRepository allocationRepository, BookingRepository bookingRepository, EventRepository eventRepository)
 {
     _allocationRepository = allocationRepository;
     _bookingRepository    = bookingRepository;
     _eventRepository      = eventRepository;
 }
        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);
            }
        }
Example #31
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);
            }
        }
Example #32
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);
            }
        }
        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));
            }
        }
Example #34
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));
            }
        }
        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);
            }
        }
        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));
            }
        }
        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);
            }
        }
Example #38
0
        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);
            }
        }
Example #39
0
        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);
            }
        }
Example #40
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 Details(int id = 0)
        {
            if (Authorized(RoleType.SystemManager))
            {
                AllocationDetailsModel model = new AllocationDetailsModel();

                using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
                {
                    model.OriginalAllocation = allocationsRep.GetEntity(id, "Budgets_AllocationToMonth");
                    model.RemainingAllocation = new Budgets_Allocations();

                    List<Orders_OrderToAllocation> approvedAllocations = model.OriginalAllocation.Orders_OrderToAllocation.Where(x => x.Order.StatusId >= (int)StatusType.InvoiceApprovedByOrderCreatorPendingFileExport).ToList();

                    foreach (var month in model.OriginalAllocation.Budgets_AllocationToMonth)
                    {
                        decimal? remainingAmount = month.Amount - approvedAllocations.Where(m => m.MonthId == month.MonthId).Select(d => (decimal?)d.Amount).Sum();

                        model.RemainingAllocation.Budgets_AllocationToMonth.Add(new Budgets_AllocationToMonth() {
                            MonthId = month.MonthId,
                            Amount = remainingAmount.HasValue ? remainingAmount.Value : 0
                        });
                    }
                }

                if (model.OriginalAllocation != null)
                {
                    if (model.OriginalAllocation.CompanyId == CurrentUser.CompanyId)
                    {
                        return View(model);
                    }
                    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);
            }
        }
Example #42
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");
        }
        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 Delete(int id = 0)
        {
            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))
                            {
                                return View(allocation);
                            }
                            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);
            }
        }
Example #45
0
        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));
                    }
                }
        }
Example #46
0
        public ActionResult ModifyStatus(string approverNotes, string selectedStatus, int id = 0)
        {
            int? historyActionId = null;
            if (!Authorized(RoleType.OrdersApprover)) return Error(Loc.Dic.error_no_permission);
            if (approverNotes != null && approverNotes.Length > 250) return Error(Loc.Dic.error_order_notes_too_long);

            Order orderFromDB;
            using (OrdersHistoryRepository ordersHistoryRep = new OrdersHistoryRepository(CurrentUser.CompanyId, CurrentUser.UserId, id))
            using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId))
            using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
            using (ApprovalRoutesRepository routesRep = new ApprovalRoutesRepository(CurrentUser.CompanyId))
            {
                orderFromDB = ordersRep.GetEntity(id, "User", "Users_ApprovalRoutes");

                if (orderFromDB == null) return Error(Loc.Dic.error_order_get_error);
                if ((orderFromDB.NextOrderApproverId != CurrentUser.UserId) && !Authorized(RoleType.SuperApprover)) return Error(Loc.Dic.error_no_permission);
                if (orderFromDB.StatusId == (int)StatusType.OrderCancelled) return Error(Loc.Dic.error_order_is_canceled);
                if (orderFromDB.StatusId >= (int)StatusType.ApprovedPendingInvoice) return Error(Loc.Dic.error_order_already_approved);

                List<Users_ApprovalStep> orderRouteSteps = orderFromDB.Users_ApprovalRoutes.Users_ApprovalStep.OrderBy(x => x.StepNumber).ToList();
                Users_ApprovalStep firstStep = orderRouteSteps.FirstOrDefault();
                Users_ApprovalStep currentStep = orderRouteSteps.Single(x => x.StepNumber == orderFromDB.ApprovalRouteStep);
                Users_ApprovalStep nextStep = orderRouteSteps.FirstOrDefault(x => x.StepNumber > currentStep.StepNumber);

                if (selectedStatus == Loc.Dic.ApproveOrder)
                {
                    if (Authorized(RoleType.SuperApprover) || nextStep == null)
                    {
                        orderFromDB.ApprovalRouteStep = null;
                        orderFromDB.NextOrderApproverId = null;
                        orderFromDB.StatusId = (int)StatusType.ApprovedPendingInvoice;
                        historyActionId = (int)HistoryActions.PassedApprovalRoute;
                    }
                    else
                    {
                        orderFromDB.ApprovalRouteStep = nextStep.StepNumber;
                        orderFromDB.NextOrderApproverId = nextStep.UserId;
                        orderFromDB.StatusId = (int)StatusType.PartiallyApproved;
                        historyActionId = (int)HistoryActions.PartiallyApproved;
                    }
                }
                else if (selectedStatus == Loc.Dic.DeclineOrder)
                {
                    orderFromDB.NextOrderApproverId = null;
                    orderFromDB.StatusId = (int)StatusType.Declined;
                    historyActionId = (int)HistoryActions.Declined;
                }
                else if (selectedStatus == Loc.Dic.SendBackToUser)
                {
                    orderFromDB.ApprovalRouteStep = firstStep.StepNumber;
                    orderFromDB.NextOrderApproverId = firstStep.UserId;
                    orderFromDB.StatusId = (int)StatusType.PendingOrderCreator;
                    historyActionId = (int)HistoryActions.ReturnedToCreator;
                }

                orderFromDB.LastStatusChangeDate = DateTime.Now;

                if (ordersRep.Update(orderFromDB) == null) return Error(Loc.Dic.error_database_error);

                Orders_History orderHistory = new Orders_History();
                if (historyActionId.HasValue) ordersHistoryRep.Create(orderHistory, historyActionId.Value, approverNotes);

                //EmailMethods emailMethods = new EmailMethods("*****@*****.**", Loc.Dic.OrdersSystem, "noreply50100200");

                //string emailSubject = String.Format("{0} {1} {2} {3} {4}", Loc.Dic.Order, orderFromDB.OrderNumber, Translation.Status((StatusType)orderFromDB.StatusId), Loc.Dic.By, CurrentUser.FullName);
                //StringBuilder emailBody = new StringBuilder();

                //emailBody.AppendLine(emailSubject);
                //emailBody.AppendLine();
                //emailBody.AppendLine(String.Format("{0}: {1}", Loc.Dic.SeeDetailsAt, Url.Action("Details", "Orders", new { id = id }, "http")));

                //emailMethods.sendGoogleEmail(orderFromDB.User.Email, orderFromDB.User.FirstName, emailSubject, emailBody.ToString());

                SendNotifications.OrderStatusChanged(orderFromDB, CurrentUser, Url);
                if (orderFromDB.StatusId == (int)StatusType.PartiallyApproved)
                    SendNotifications.OrderPendingApproval(orderFromDB, Url);

                return RedirectToAction("PendingOrders");
            }
        }
Example #47
0
        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 }));
                        }
        }
Example #48
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_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);
            }
        }
Example #50
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";
        }