Esempio n. 1
0
        private void ValidateBreaks(List <CreateBreak> breaks)
        {
            foreach (var b in breaks)
            {
                try
                {
                    b.Validate();
                }
                catch (BreakTypeException ex)
                {
                    ModelState.AddModelError(
                        nameof(CreateBreak.BreakType), BreakTypeValueErrorMessage(ex)
                        );
                }
            }

            _salesAreaRepository.ValidateSaleArea(breaks.Select(s => s.SalesArea).ToList());

            // Local functions
            string BreakTypeValueErrorMessage(Exception ex)
            {
                const string FieldName = nameof(CreateBreak.ExternalBreakRef);

                var errorMessage = new StringBuilder(200);

                errorMessage.Append(ex.Message);
                errorMessage.Append(" ");
                errorMessage.Append(FieldName);
                errorMessage.Append(" :: ");
                errorMessage.Append(ex.Data[FieldName]);

                return(errorMessage.ToString());
            }
        }
Esempio n. 2
0
        private void ValidatePrograms(List <CreateProgramme> programs)
        {
            //Required field validation
            programs.ForEach(b =>
            {
                Validate(b.SalesArea, b.StartDateTime, b.Duration, b.ExternalReference, b.ProgrammeName);
            });
            var programcategorysList = programs.Where(p => p.ProgrammeCategories != null)
                                       .SelectMany(b => b.ProgrammeCategories)
                                       .Where(p => !string.IsNullOrWhiteSpace(p)).ToList();

            //Validation for category type
            if (programcategorysList.Count > 0 && !_programmeCategoryRepository.IsValid(programcategorysList, out List <string> invaliddata))
            {
                var msg = "category names are invalid";
                if (invaliddata == null || invaliddata.Count <= 0)
                {
                    throw new InvalidDataException(msg);
                }

                msg = msg + ": " + string.Join(",", invaliddata);
                throw new InvalidDataException(msg);
            }

            _salesAreaRepository.ValidateSaleArea(programs.Select(s => s.SalesArea).ToList());
        }
Esempio n. 3
0
        public void ValidateUniverse(List <CreateUniverse> commands)
        {
            commands.ForEach(command => Validate(command.SalesArea, command.Demographic, command.StartDate,
                                                 command.EndDate, command.UniverseValue));

            _salesAreaRepository.ValidateSaleArea(commands.Select(_ => _.SalesArea).ToList());
            if (!_demographicRepository.ValidateDemographics(commands.Select(u => u.Demographic).ToList(),
                                                             out List <string> invalidDemographics))
            {
                var msg = string.Concat("Invalid Demographics: ",
                                        invalidDemographics != null ? string.Join(",", invalidDemographics) : string.Empty);
                throw new InvalidDataException(msg);
            }
        }
Esempio n. 4
0
        private void ValidateInput(CreateRestriction command)
        {
            if (!string.IsNullOrWhiteSpace(command.ExternalIdentifier))
            {
                var restriction = _restrictionRepository.Get(command.ExternalIdentifier);
                if (restriction != null)
                {
                    var msg = $"Restriction with external identifier: '{command.ExternalIdentifier}' already exists";
                    throw new InvalidDataException(msg);
                }
            }

            ValidateRestrictionDatesAndDays(command.StartDate, command.EndDate, command.RestrictionDays);

            if (command.SalesAreas != null && command.SalesAreas.Any())
            {
                _salesAreaRepository.ValidateSaleArea(command.SalesAreas);
            }

            CustomValidation(command);

            if (!string.IsNullOrWhiteSpace(command.ProgrammeCategory) && !_programmeCategoryRepository.IsValid(
                    new List <string> {
                command.ProgrammeCategory
            },
                    out List <string> invalidList))
            {
                var msg = string.Concat("Invalid programme category: ",
                                        invalidList != null ? invalidList.FirstOrDefault() : string.Empty);
                throw new InvalidDataException(msg);
            }

            if (!string.IsNullOrWhiteSpace(command.ClearanceCode))
            {
                _clearanceRepository.ValidateClearanceCode(new List <string> {
                    command.ClearanceCode
                });
            }
        }
Esempio n. 5
0
        /// <summary>Validates the campaigns to create have valid data.</summary>
        /// <param name="campaigns">The campaigns to validate.</param>
        /// <param name="validateCampaignPassPriority">If set to <c>true</c>
        /// validate campaign pass priority.</param>
        private void ValidateCampaigns(List <CreateCampaign> campaigns, bool validateCampaignPassPriority = true)
        {
            var validateDeliveryType = _featureManager.IsEnabled(nameof(ProductFeature.CampaignDeliveryType));

            // Required and Regex Validation
            campaigns.ForEach(c =>
            {
                if (c?.ProgrammesList != null)
                {
                    _mapper.Map <List <CampaignProgramme> >(c.ProgrammesList);
                }

                List <CampaignProgramme> campaignProgrammesPlacebo = null;

                Validation(c.ExternalId, c.Name, c.DemoGraphic, c.StartDateTime, c.EndDateTime, c.Product, c.DeliveryType,
                           c.TargetRatings, c.SalesAreaCampaignTarget, c.TimeRestrictions, c.ProgrammeRestrictions, campaignProgrammesPlacebo, c.CampaignGroup,
                           c.IncludeRightSizer, c.IncludeOptimisation, c.CampaignPassPriority, c.CampaignSpotMaxRatings, validateCampaignPassPriority,
                           validateDeliveryType);
            });

            if (!_demographicRepository.ValidateDemographics(
                    campaigns.Select(c => c.DemoGraphic).ToList(),
                    out List <string> invalidDemographic)
                )
            {
                var msg = String.Concat(
                    "Invalid Demographic in Campaigns: ",
                    invalidDemographic is null ?
                    String.Empty :
                    String.Join(",", invalidDemographic));

                throw new InvalidDataException(msg);
            }

            _productRepository.ValidateProductExternalIds(campaigns.Select(c => c.Product).ToList());

            var salesAreaCampaignTargets = campaigns
                                           .Where(p => p.SalesAreaCampaignTarget != null && p.SalesAreaCampaignTarget.Count > 0)
                                           .SelectMany(b => b.SalesAreaCampaignTarget)
                                           .ToList();

            if (salesAreaCampaignTargets.Any())
            {
                var salesAreas = salesAreaCampaignTargets
                                 .Where(s => s.SalesAreaGroup != null && s.SalesAreaGroup.SalesAreas != null &&
                                        s.SalesAreaGroup.SalesAreas.Any())
                                 .SelectMany(s => s.SalesAreaGroup.SalesAreas)
                                 .ToList();

                _salesAreaRepository.ValidateSaleArea(salesAreas);
            }

            var programmeRestrictions = campaigns
                                        .Where(c => c.ProgrammeRestrictions != null && c.ProgrammeRestrictions.Count > 0)
                                        .SelectMany(c => c.ProgrammeRestrictions)
                                        .ToList();

            if (programmeRestrictions.Any())
            {
                var saleAreas = programmeRestrictions.Where(p => p.SalesAreas != null && p.SalesAreas.Any())
                                .SelectMany(p => p.SalesAreas)
                                .ToList();

                if (saleAreas.Any())
                {
                    _salesAreaRepository.ValidateSaleArea(saleAreas);
                }

                var categoryNames = programmeRestrictions
                                    .Where(p => p.IsCategoryOrProgramme.Equals(CategoryOrProgramme.C.ToString(), StringComparison.OrdinalIgnoreCase))
                                    ?.SelectMany(p => p.CategoryOrProgramme)
                                    ?.ToList();

                if (categoryNames.Any() && !_programmeCategoryRepository.IsValid(categoryNames, out List <string> invalidCategory))
                {
                    var msg = String.Concat(
                        "Invalid Category Name: ",
                        invalidCategory is null ?
                        String.Empty
                            : String.Join(",", invalidCategory)
                        );

                    throw new InvalidDataException(msg);
                }
            }

            var timeRestrictions = campaigns
                                   .Where(c => c.TimeRestrictions != null && c.TimeRestrictions.Count > 0)
                                   .SelectMany(c => c.TimeRestrictions)
                                   .ToList();

            if (timeRestrictions.Any())
            {
                var saleAreas = timeRestrictions.Where(p => p.SalesAreas != null && p.SalesAreas.Any())
                                .SelectMany(p => p.SalesAreas)
                                .ToList();

                if (saleAreas.Any())
                {
                    _salesAreaRepository.ValidateSaleArea(saleAreas);
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Validates for saving run
        /// </summary>
        /// <param name="run"></param>
        /// <param name="allScenarios"></param>
        /// <param name="allPassesByScenario"></param>
        public void ValidateForSave(
            Run run,
            List <Scenario> allScenarios,
            List <List <Pass> > allPassesByScenario,
            List <SalesArea> allSalesAreas)
        {
            // Basic validation
            Run.ValidateForSave(run);

            ValidateAnalysisGroupTargets(run.AnalysisGroupTargets);

            if (run.RunTypeId != 0)
            {
                if (_featureManager.IsEnabled(nameof(ProductFeature.RunType)))
                {
                    var runType = _runTypeRepository.Get(run.RunTypeId);
                    if (runType is null || runType.Hidden)
                    {
                        throw new Exception("Run type not found");
                    }
                }
                else
                {
                    run.RunTypeId = 0;
                }
            }

            if (run.Scenarios.Count > 1 && !_brsConfigurationTemplateRepository.Exists(run.BRSConfigurationTemplateId))
            {
                throw new Exception("BRS template not found");
            }

            RunsValidations.ValidateScenarios(allScenarios);

            // validate all passes
            for (int index = 0; index < allPassesByScenario.Count; index++)
            {
                allPassesByScenario[index]?.ForEach(pass =>
                {
                    Pass.ValidateForSave(pass);
                    Pass.ValidateScenarioNamingUniqueness(pass, new List <Scenario>()
                    {
                        allScenarios[index]
                    });
                });
            }

            // Check that run doesn't contain default scenario, can only contain
            // a copy
            TenantSettings tenantSettings = _tenantSettingsRepository.Get();

            if (tenantSettings.DefaultScenarioId != Guid.Empty && run.Scenarios.Where(s => s.Id == tenantSettings.DefaultScenarioId).Any())
            {
                throw new Exception("Run cannot contain the default scenario. It must contain a copy");
            }

            if (string.IsNullOrWhiteSpace(tenantSettings.PeakStartTime) ||
                string.IsNullOrWhiteSpace(tenantSettings.PeakEndTime))
            {
                throw new ArgumentNullException(nameof(tenantSettings), "Peak daypart is not set. Please check the tenant settings.");
            }

            if (string.IsNullOrWhiteSpace(tenantSettings.MidnightStartTime) ||
                string.IsNullOrWhiteSpace(tenantSettings.MidnightEndTime))
            {
                throw new ArgumentNullException(nameof(tenantSettings), "Midnight daypart is not set. Please check the tenant settings.");
            }

            // Check sales areas priorities
            if (run.SalesAreaPriorities != null && run.SalesAreaPriorities.Any())
            {
                var existingSalesAreaNames = new HashSet <string>(allSalesAreas.Select(s => s.Name));
                var runSalesAreaNames      = new HashSet <string>();

                var  unknownSalesAreas    = new List <string>();
                var  duplicatedSalesAreas = new List <string>();
                bool areAllExcluded       = true;

                foreach (var priority in run.SalesAreaPriorities)
                {
                    if (!existingSalesAreaNames.Contains(priority.SalesArea))
                    {
                        unknownSalesAreas.Add(priority.SalesArea);
                    }

                    if (runSalesAreaNames.Contains(priority.SalesArea))
                    {
                        duplicatedSalesAreas.Add(priority.SalesArea);
                    }

                    if (priority.Priority != SalesAreaPriorityType.Exclude)
                    {
                        areAllExcluded = false;
                    }

                    runSalesAreaNames.Add(priority.SalesArea);
                }

                if (unknownSalesAreas.Any())
                {
                    throw new Exception(string.Format("Sales area {0} is not valid", unknownSalesAreas[0]));
                }

                if (areAllExcluded)
                {
                    throw new Exception("All Sales area priorities are set to Exclude");
                }

                if (duplicatedSalesAreas.Any())
                {
                    throw new Exception(string.Format("Run Sales area priorities contains duplicate {0}", duplicatedSalesAreas[0]));
                }
            }

            // Get runs & scenarios
            var runsWithScenarioId = _runRepository.GetRunsWithScenarioId();

            // Get scenarios & passes
            var scenariosWithPassId = _scenarioRepository.GetScenariosWithPassId();

            if (run.Scenarios != null && run.Scenarios.Any())
            {
                var runSalesAreas        = run.SalesAreaPriorities?.Where(sa => sa.Priority != SalesAreaPriorityType.Exclude).Select(x => x.SalesArea).ToList();
                var salesAreasToValidate = new List <string>();

                for (int scenarioIndex = 0; scenarioIndex < run.Scenarios.Count; scenarioIndex++)
                {
                    var scenario = run.Scenarios[scenarioIndex];
                    var passes   = allPassesByScenario[scenarioIndex];

                    // Check that scenario isn't linked to another run
                    var otherRunIdsForScenarioId = runsWithScenarioId.Where(rws => rws.ScenarioId == scenario.Id && rws.RunId != run.Id).Select(rws => rws.RunId).ToList();
                    if (otherRunIdsForScenarioId.Any())
                    {
                        var otherRun = _runRepository.Find(otherRunIdsForScenarioId.First());
                        throw new Exception(string.Format("Scenario is already linked to Run {0}", otherRun.Description));
                    }

                    if (passes != null && passes.Any())
                    {
                        foreach (var pass in passes)
                        {
                            // Check that passes aren't linked to other scenarios
                            var otherScenarioIdsForPassId = scenariosWithPassId.Where(swp => swp.PassId == pass.Id && swp.ScenarioId != scenario.Id).Select(swp => swp.ScenarioId).ToList();
                            if (otherScenarioIdsForPassId.Any())
                            {
                                var otherScenario = _scenarioRepository.Get(otherScenarioIdsForPassId.First());
                                throw new Exception(string.Format("Pass is already linked to Scenario {0}", otherScenario.Name));
                            }

                            // Check that passes aren't linked to other
                            // scenarios in this run
                            if (pass.Id > 0)
                            {
                                if (passes.Where(p => p.Id == pass.Id).ToList().Count > 1)
                                {
                                    throw new Exception("Scenario cannot contain multiple instances of the same PassID");
                                }

                                for (int scenarioIndex2 = 0; scenarioIndex2 < run.Scenarios.Count; scenarioIndex2++)
                                {
                                    if (scenarioIndex != scenarioIndex2)
                                    {
                                        if (allPassesByScenario[scenarioIndex2].Select(p => p.Id).Contains(pass.Id))
                                        {
                                            throw new Exception("Pass is already linked to another Scenario for this run");
                                        }
                                    }
                                }
                            }

                            var errorMsg = RunsValidations.ValidatePassSalesAreaPriorities(run, pass, tenantSettings, runSalesAreas);
                            if (!string.IsNullOrWhiteSpace(errorMsg))
                            {
                                throw new Exception(errorMsg);
                            }
                        }
                    }

                    // Check break exclusions
                    if (passes != null && passes.Any() && passes.Any(p => p.BreakExclusions != null && p.BreakExclusions.Any()))
                    {
                        var breakExclusions = passes
                                              .Where(p => p?.BreakExclusions != null && p.BreakExclusions.Any())
                                              .SelectMany(p => p.BreakExclusions)
                                              .Select(b => b.SalesArea);

                        salesAreasToValidate.AddRange(breakExclusions);
                    }
                }

                if (salesAreasToValidate.Any())
                {
                    _salesAreaRepository.ValidateSaleArea(salesAreasToValidate);
                }
            }

            // Check campaigns
            if (run.Campaigns != null && run.Campaigns.Count > 0)
            {
                var existingCampaigns = new HashSet <string>(_campaignRepository.GetAllFlat().Select(x => x.ExternalId));
                var unknownCampaigns  = run.Campaigns.Select(ca => ca.ExternalId)
                                        .Where(externalId => !existingCampaigns.Contains(externalId)).ToList();
                if (unknownCampaigns.Any())
                {
                    throw new Exception(string.Format("Campaign {0} is not valid", unknownCampaigns[0]));
                }
            }

            // Validation for slotting control by Demograph
            if (run.Scenarios != null && run.Scenarios.Any())
            {
                var demographicsToValidate = new List <string>();

                for (int scenarioIndex = 0; scenarioIndex < run.Scenarios.Count; scenarioIndex++)
                {
                    var passes = allPassesByScenario[scenarioIndex];

                    if (passes != null && passes.Any() && passes.Any(p => p.SlottingLimits != null && p.SlottingLimits.Any()))
                    {
                        var slottingLimits = passes
                                             .Where(p => p?.SlottingLimits != null && p.SlottingLimits.Any())
                                             .SelectMany(p => p.SlottingLimits)
                                             .Select(b => b.Demographs);

                        demographicsToValidate.AddRange(slottingLimits);
                    }
                }

                demographicsToValidate = demographicsToValidate.Where(x => x != null).Distinct().ToList();

                if (demographicsToValidate.Any() && !_demographicRepository.ValidateDemographics(demographicsToValidate,
                                                                                                 out List <string> invalidDemographics))
                {
                    var msg = string.Concat(
                        "Invalid Demographic in slotting control by Demograph: ",
                        invalidDemographics != null
                            ? string.Join(",", invalidDemographics)
                            : string.Empty);
                    throw new InvalidDataException(msg);
                }
            }

            ValidateDeliveryCappingGroupIds(_mapper.Map <IEnumerable <CampaignRunProcessesSettingsModel> >(run.CampaignsProcessesSettings));
        }