Ejemplo n.º 1
0
        public IHttpActionResult Post([FromBody] CreatePassModel command)
        {
            // Check empty name
            if (string.IsNullOrWhiteSpace(command.Name))
            {
                return(this.Error().InvalidParameters("Pass name must be set"));
            }

            if (!ModelState.IsValid)
            {
                return(this.Error().InvalidParameters("Invalid pass parameters"));
            }

            // Check that pass doesn't exist
            Pass pass = _passRepository.Get(command.Id);

            if (pass != null)
            {
                return(this.Error().InvalidParameters("Pass already exists"));
            }

            // Check that pass with such name doesn't exist
            pass = _passRepository.FindByName(command.Name, command.IsLibraried);
            if (pass != null)
            {
                return(this.Error().InvalidParameters("Pass with such name already exists"));
            }

            if (_passInspectorService.InspectPassSalesAreaPriorities(
                    command.PassSalesAreaPriorities,
                    out string errorMessage))
            {
                return(this.Error().InvalidParameters(errorMessage));
            }

            List <string> breakExclusionsErrorMessages = new List <string>();

            if (!BreakExclusionsValidations.DateTimeRangeIsValid(command.BreakExclusions, _salesAreaRepository.GetAll(), out breakExclusionsErrorMessages))
            {
                return(this.Error().InvalidParameters(breakExclusionsErrorMessages));
            }

            pass = _mapper.Map <Pass>(command);
            IdUpdater.SetIds(pass, _identityGeneratorResolver);

            // Validate
            ValidateForSave(pass);

            // Save
            _passRepository.Add(pass);
            _passRepository.SaveChanges();   // Do not remove this, need to persist changes now so that we can return PassModel

            return(Ok(Mappings.MapToPassModel(pass, _passRepository, _mapper)));
        }
Ejemplo n.º 2
0
        public IHttpActionResult Put([FromUri] int id, [FromBody] PassModel command)
        {
            // Check empty name
            if (string.IsNullOrWhiteSpace(command.Name))
            {
                return(this.Error().InvalidParameters("No name was entered"));
            }

            if (!ModelState.IsValid)
            {
                return(this.Error().InvalidParameters("Invalid pass parameters"));
            }

            var pass = _passRepository.Get(id);

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

            var pass2 = _passRepository.FindByName(command.Name, command.IsLibraried);

            if (pass2 != null && pass.Id != pass2.Id)
            {
                return(this.Error().InvalidParameters("Pass with such name already exists"));
            }

            if (_passInspectorService.InspectPassSalesAreaPriorities(
                    command.PassSalesAreaPriorities,
                    out string errorMessage))
            {
                return(this.Error().InvalidParameters(errorMessage));
            }

            List <string> breakExclusionsErrorMessages = new List <string>();

            if (!BreakExclusionsValidations.DateTimeRangeIsValid(command.BreakExclusions, _salesAreaRepository.GetAll(), out breakExclusionsErrorMessages))
            {
                return(this.Error().InvalidParameters(breakExclusionsErrorMessages));
            }

            Mappings.ApplyToPass(pass, command, _mapper);
            IdUpdater.SetIds(pass, _identityGeneratorResolver);

            // Validate
            ValidateForSave(pass);

            // Save
            _passRepository.Update(pass);
            _passRepository.SaveChanges();   // Do not remove this, need to persist changes now so that we can return PassModel

            return(Ok(Mappings.MapToPassModel(pass, _passRepository, _mapper)));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Creates run from template
        /// </summary>
        /// <param name="templateRun"></param>
        /// <param name="runRepository"></param>
        /// <returns></returns>
        private Run CreateRunFromTemplate(Run templateRun, IRunRepository runRepository)
        {
            using (var scope = _repositoryFactory.BeginRepositoryScope())
            {
                // Get sales areas for the run
                var salesAreaRepository = scope.CreateRepository <ISalesAreaRepository>();

                var salesAreas = RunManager.GetSalesAreas(templateRun, salesAreaRepository.GetAll());

                // Set the default run start date time using today's date and time from template run, use it as the starting point to try and
                // find some schedule data.
                DateTime startingDateTime = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, templateRun.StartDate.Hour, templateRun.StartDate.Minute, templateRun.StartDate.Second, templateRun.StartDate.Millisecond, templateRun.StartDate.Kind);

                // Clone template run, reset it, set date range
                Run cloneRun = (Run)templateRun.Clone();
                cloneRun.Id                     = Guid.NewGuid();
                cloneRun.Description            = $"Deployment Test ({GetVersion().Version})";
                cloneRun.CreatedDateTime        = DateTime.UtcNow;
                cloneRun.ExecuteStartedDateTime = null;
                cloneRun.LastModifiedDateTime   = cloneRun.CreatedDateTime;
                cloneRun.IsLocked               = false;
                cloneRun.Scenarios.ForEach(scenario => scenario.ResetToPendingStatus());
                cloneRun.StartDate = GetRunStartDate(startingDateTime, salesAreas, 90);
                if (cloneRun.StartDate == DateTime.MaxValue)
                {
                    throw new Exception("Unable to determine start date for test run due to insufficient data");
                }
                cloneRun.EndDate = cloneRun.StartDate.AddDays(1);
                cloneRun.Real    = false;  // Flag that it's not a real run

                // Clear IDs so that we can assign new ones
                //IdUpdater.ClearIds(cloneRun);
                cloneRun.Id       = Guid.Empty;
                cloneRun.CustomId = 0;

                // Set new IDs
                IdUpdater.SetIds(cloneRun, _identityGeneratorResolver);

                // Save run
                runRepository.Add(cloneRun);
                runRepository.SaveChanges();
                return(cloneRun);
            }
        }
Ejemplo n.º 4
0
        //[ResponseType(typeof(PassModel))]
        public IHttpActionResult PostCreateTestData([FromUri] int numberOfPasses, int cloneFromPassId = 0)
        {
            var passes = _passRepository.GetAll().OrderBy(p => p.Id).ToList();

            if (!passes.Any())
            {
                return(this.Error().UnknownError("No passes to clone from"));
            }
            var templatePass = cloneFromPassId == 0 ? passes.First() : passes.FirstOrDefault(p => p.Id == cloneFromPassId);

            if (templatePass == null)
            {
                return(this.Error().InvalidParameters("Pass to clone from does not exist"));
            }
            if (numberOfPasses < 1)
            {
                return(this.Error().InvalidParameters("Number of passes to create is invalid"));
            }
            else if (numberOfPasses > 100)
            {
                return(this.Error().InvalidParameters("Number of passes to create is too large"));
            }

            // Create new passes from
            var newPasses = new List <Pass>();

            for (int passIndex = 0; passIndex < numberOfPasses; passIndex++)
            {
                var pass = (Pass)templatePass.Clone();
                pass.Id = 0;
                IdUpdater.SetIds(pass, _identityGeneratorResolver);
                pass.Name = $"Pass {pass.Id}";
                newPasses.Add(pass);
            }

            _passRepository.Add(newPasses);
            _passRepository.SaveChanges();
            return(Ok());
        }
Ejemplo n.º 5
0
        public IHttpActionResult PutScenario([FromUri] Guid id, [FromBody] ScenarioModel command)
        {
            // Check empty name
            if (string.IsNullOrWhiteSpace(command.Name))
            {
                return(this.Error().InvalidParameters("No name was entered"));
            }

            if (!ModelState.IsValid)
            {
                return(this.Error().InvalidParameters("Invalid scenario parameters"));
            }

            var scenario = _scenarioRepository.Get(id);

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

            var scenario2 = _scenarioRepository.FindByName(command.Name, command.IsLibraried);

            if (scenario2 != null && scenario.Id != scenario2.Id)
            {
                return(this.Error().InvalidParameters("Scenario with such name already exists"));
            }

            var salesAreas = _salesAreaRepository.GetAll();

            foreach (var pass in command.Passes)
            {
                if (_passInspectorService.InspectPassSalesAreaPriorities(
                        pass.PassSalesAreaPriorities,
                        out string errorMessage))
                {
                    return(this.Error().InvalidParameters(errorMessage));
                }

                List <string> errorMessages = new List <string>();
                if (!BreakExclusionsValidations.DateTimeRangeIsValid(pass.BreakExclusions, salesAreas, out errorMessages))
                {
                    return(this.Error().InvalidParameters(errorMessages));
                }
            }

            var oldPassIds = scenario.Passes.Select(p => p.Id).ToList();

            // Get PassIds to delete
            var deletedPassIds = oldPassIds.Except(command.Passes.Select(p => p.Id)).Distinct().ToList();

            ValidateCampaignPriorityRounds(command.CampaignPriorityRounds);

            Mappings.ApplyToScenario(scenario, command, _mapper);
            IdUpdater.SetIds(scenario, _identityGeneratorResolver);

            // Update Pass repository
            UpdatePassRepository(scenario, command, deletedPassIds);
            _passRepository.SaveChanges();

            // update scenario with any changes to passes in that scenario.campaignpasspriorities
            UpdateScenarioWithEditedPassList(scenario, oldPassIds, deletedPassIds);

            // Validate, update and save scenario
            ValidateForSave(scenario);

            scenario.DateUserModified = DateTime.UtcNow;

            _scenarioRepository.Update(new List <Scenario> {
                scenario
            });                                  // Used bulk update method as a temporary solution as it is optimized to update nested collections
                                                 // Will be changed in scope of performance optimizations phase 2
            _scenarioRepository.SaveChanges();   // Do not remove this, need to persist changes now so that we can return ScenarioModel

            return(Ok(Mappings.MapToScenarioModel(scenario, _scenarioRepository, _passRepository,
                                                  _tenantSettingsRepository, _mapper)));
        }
Ejemplo n.º 6
0
        public IHttpActionResult PostScenario([FromBody] CreateScenarioModel command)
        {
            // Check empty name
            if (string.IsNullOrWhiteSpace(command.Name))
            {
                return(this.Error().InvalidParameters("No name was entered"));
            }

            if (!ModelState.IsValid)
            {
                return(this.Error().InvalidParameters("Invalid scenario parameters"));
            }

            // Check that scenario doesn't exist
            Scenario scenario = _scenarioRepository.Get(command.Id);

            if (scenario != null)
            {
                return(this.Error().InvalidParameters("Scenario already exists"));
            }

            // Check that scenario with such name doesn't exist
            scenario = _scenarioRepository.FindByName(command.Name, command.IsLibraried);
            if (scenario != null)
            {
                return(this.Error().InvalidParameters("Scenario with such name already exists"));
            }

            foreach (var pass in command.Passes)
            {
                if (_passInspectorService.InspectPassSalesAreaPriorities(
                        pass.PassSalesAreaPriorities,
                        out string errorMessage))
                {
                    return(this.Error().InvalidParameters(errorMessage));
                }

                List <string> errorMessages = new List <string>();

                if (!BreakExclusionsValidations.DateTimeRangeIsValid(pass.BreakExclusions, _salesAreaRepository.GetAll(), out errorMessages))
                {
                    return(this.Error().InvalidParameters(errorMessages));
                }
            }

            ValidateCampaignPriorityRounds(command.CampaignPriorityRounds);

            // Add scenario
            scenario = _mapper.Map <Scenario>(command);

            IdUpdater.SetIds(scenario, _identityGeneratorResolver);

            // Update Pass repository
            UpdatePassRepository(scenario, command, null);
            _passRepository.SaveChanges();

            // Add Campaign Pass Priorities to Scenario
            var campaignsResult   = _campaignRepository.GetWithProduct(null);
            var usingAllCampaigns = campaignsResult.Items?.Any() == true?campaignsResult.Items.ToList() : null;

            var forScenarioPasses = _passRepository.FindByIds(scenario.Passes.Select(p => p.Id)).ToList();

            var allCampaigns = usingAllCampaigns?.ToDictionary(x => x.ExternalId, x => x);

            CampaignPassPrioritiesServiceMapper.AmendCampaignPassPrioritiesForNewCampaigns(
                scenario,
                forScenarioPasses,
                allCampaigns,
                _passRepository,
                _mapper);

            // Validate
            ValidateForSave(scenario);

            scenario.DateUserModified = DateTime.UtcNow;

            // Add scenario
            _scenarioRepository.Add(scenario);
            _scenarioRepository.SaveChanges();   // Do not remove this, need to persist changes now so that we can return ScenarioModel

            return(Ok(Mappings.MapToScenarioModel(scenario, _scenarioRepository, _passRepository,
                                                  _tenantSettingsRepository, _mapper)));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates template run, all run options selected, single sales area, default scenario. The template run can be manually modified
        /// later.
        /// </summary>
        /// <param name="runId"></param>
        private void CreateRunForTemplate(Guid runId)
        {
            using (var scope = _repositoryFactory.BeginRepositoryScope())
            {
                var repositories = scope.CreateRepositories(
                    typeof(IRunRepository),
                    typeof(ISalesAreaRepository),
                    typeof(ITenantSettingsRepository)
                    );
                var runRepository            = repositories.Get <IRunRepository>();
                var tenantSettingsRepository = repositories.Get <ITenantSettingsRepository>();
                var salesAreaRepository      = repositories.Get <ISalesAreaRepository>();

                // Get sales areas
                var salesAreas = salesAreaRepository.GetAll();

                // Get tenant settings with default scenario
                var tenantSettings = tenantSettingsRepository.Get();

                // Create run, single sales area
                Run run = new Run()
                {
                    Id              = runId,
                    Description     = "Template",
                    CreatedDateTime = DateTime.UtcNow,
                    //StartDateTime = DateTime.UtcNow.Date,
                    //EndDateTime = DateTime.UtcNow.Date.AddDays(48),
                    IsLocked     = false,
                    Optimisation = true,
                    Smooth       = true,
                    ISR          = true,
                    RightSizer   = true,
                    Real         = false,
                    Author       = new AuthorModel()
                    {
                        Id   = 1,
                        Name = "User"
                    }
                };
                run.SalesAreaPriorities.Add(new SalesAreaPriority()
                {
                    SalesArea = salesAreas.OrderBy(sa => sa.Name).First().Name,
                    Priority  = SalesAreaPriorityType.Priority3
                });

                // Add scenario
                var runScenario = new RunScenario()
                {
                    Id = tenantSettings.DefaultScenarioId
                };
                run.Scenarios.Add(runScenario);
                //Scenario scenario = (Scenario)tenantSettings.DefaultScenario.Clone();
                run.Scenarios.ForEach(s => s.ResetToPendingStatus());
                //run.Scenarios.Add(scenario);

                // Set new IDs
                IdUpdater.SetIds(run, _identityGeneratorResolver);

                // Save run
                runRepository.Add(run);
                runRepository.SaveChanges();
            }
        }