public ValidationHelper(RemoteValidationContext model, RemoteValidationResult result, IConnectionProvider provider, ISettingsService settingsService)
 {
     Model            = model;
     Result           = result;
     _provider        = provider;
     _settingsService = settingsService;
 }
        public ActionResult Validate(string validatorKey, [FromBody] RemoteValidationContext context)
        {
            HttpContextUserProvider.ForcedUserId = 1;
            var result = new RemoteValidationResult();

            try
            {
                var errorMessage = _consolidationFactory.Validate(context.CustomerCode);

                if (errorMessage != null)
                {
                    result.Messages.Add(errorMessage);
                }
                else
                {
                    result = _validationFactory(validatorKey).Validate(context, result);
                }
            }
            catch (ResolutionFailedException ex)
            {
                result.Messages.Add("Validator " + validatorKey + " is not registered: " + ex.Message);
            }
            catch (ValidationException ex)
            {
                result.Messages.Add(ex.Message);
            }
            HttpContextUserProvider.ForcedUserId = 0;

            return(Json(result));
        }
Exemple #3
0
        public RemoteValidationResult Validate(RemoteValidationContext model, RemoteValidationResult result)
        {
            var helper = new ValidationHelper(model, result, _provider, _service);

            var productTypeName = _service.GetSetting(SettingsTitles.PRODUCT_TYPES_FIELD_NAME);



            using (new QPConnectionScope(helper.Customer.ConnectionString, (DatabaseType)helper.Customer.DatabaseType))
            {
                var articleSerivce = new ArticleService(helper.Customer.ConnectionString, 1);
                var emptyArticle   = articleSerivce.New(model.ContentId);

                var productsName           = helper.GetRelatedFieldName(emptyArticle, helper.GetSettingValue(SettingsTitles.PRODUCTS_CONTENT_ID));
                var marketingProductTypeId = helper.GetValue <int>(helper.GetClassifierFieldName(emptyArticle));
                var productIds             = helper.GetValue <ListOfInt>(productsName);

                if (productIds != null && AreTypesIncompatible(helper, articleSerivce, marketingProductTypeId, productIds, productTypeName))
                {
                    var message = new ActionTaskResultMessage()
                    {
                        ResourceClass = ValidationHelper.ResourceClass,
                        ResourceName  = nameof(RemoteValidationMessages.SameTypeMarketingProductProducts),
                    };
                    result.AddModelError(helper.GetPropertyName(productsName), helper.ToString(message));
                    return(result);
                }

                if (!GetUniqueAliasExclusions(helper).Contains(marketingProductTypeId))
                {
                    var ids = CheckAliasUniqueness(helper, marketingProductTypeId, articleSerivce, productTypeName);
                    if (!String.IsNullOrEmpty(ids))
                    {
                        var message = new ActionTaskResultMessage()
                        {
                            ResourceClass = ValidationHelper.ResourceClass,
                            ResourceName  = nameof(RemoteValidationMessages.MarketingProduct_Duplicate_Alias),
                            Parameters    = new object[] { ids }
                        };

                        result.AddModelError(
                            helper.GetPropertyName(Constants.FieldAlias), helper.ToString(message)
                            );
                    }
                }
            }

            return(result);
        }
        public RemoteValidationResult Validate(RemoteValidationContext context, RemoteValidationResult result)
        {
            var filterDefinition = context.Definitions.FirstOrDefault(x => x.Alias == FieldFilter);

            if (filterDefinition == null)
            {
                var message = new ActionTaskResultMessage()
                {
                    ResourceClass = ValidationHelper.ResourceClass,
                    ResourceName  = nameof(RemoteValidationMessages.MissingParam),
                    Parameters    = new object[] { FieldFilter }
                };
                result.AddErrorMessage(ValidationHelper.ToString(context, message));
            }
            else
            {
                var filter = context.ProvideValueExact <string>(filterDefinition);
                if (string.IsNullOrEmpty(filter))
                {
                    return(result);
                }
                var normalizedFilter = DPathProcessor.NormalizeExpression(filter);
                if (!DPathProcessor.IsExpressionValid(normalizedFilter))
                {
                    var message = new ActionTaskResultMessage()
                    {
                        ResourceClass = ValidationHelper.ResourceClass,
                        ResourceName  = nameof(RemoteValidationMessages.InvalidFilter),
                        Parameters    = new object[] { normalizedFilter }
                    };
                    result.AddModelError(filterDefinition.PropertyName, ValidationHelper.ToString(context, message));
                }
            }


            return(result);
        }
        public RemoteValidationResult Validate(RemoteValidationContext model, RemoteValidationResult result)
        {
            var helper = new ValidationHelper(model, result, _provider, _service);

            int productTypesContentId = helper.GetSettingValue(SettingsTitles.PRODUCT_TYPES_CONTENT_ID);
            var marketingContentId    = helper.GetSettingValue(SettingsTitles.MARKETING_PRODUCT_CONTENT_ID);
            var parametersContentId   = helper.GetSettingValue(SettingsTitles.PRODUCTS_PARAMETERS_CONTENT_ID);
            var regionsContentId      = helper.GetSettingValue(SettingsTitles.REGIONS_CONTENT_ID);

            var contentId = model.ContentId;
            int productId = helper.GetValue <int>(Constants.FieldId);

            using (new QPConnectionScope(helper.Customer.ConnectionString, (DatabaseType)helper.Customer.DatabaseType))
            {
                var articleService = new ArticleService(helper.Customer.ConnectionString, 1);

                var product         = productId > 0 ? articleService.Read(productId) : articleService.New(contentId);
                var markProductName = helper.GetRelatedFieldName(product, marketingContentId);
                var markProductId   = helper.GetValue <int>(markProductName);
                var markProduct     = articleService.Read(markProductId);
                var productsName    = helper.GetRelatedFieldName(markProduct, contentId);

                var productTypeName = helper.GetClassifierFieldName(product);
                int typeId          = helper.GetValue <int>(productTypeName);

                var regionsName = helper.GetRelatedFieldName(product, regionsContentId);

                var parametersName = helper.GetRelatedFieldName(product, parametersContentId);

                int[] regionsIds    = helper.GetValue <ListOfInt>(regionsName).ToArray();
                int[] parametersIds = helper.GetValue <ListOfInt>(parametersName)?.ToArray();


                helper.CheckSiteId(productTypesContentId);

                //Проверка того, что продукт не имеет общих регионов с другими региональными продуктами этого МП
                var productsIds = markProduct
                                  .FieldValues.Where(a => a.Field.Name == productsName)
                                  .SelectMany(a => a.RelatedItems)
                                  .ToArray();

                helper.IsProductsRegionsWithModifierIntersectionsExist(articleService, productId, regionsIds,
                                                                       productsIds,
                                                                       regionsName, Constants.FieldProductModifiers, 0);


                if (productId > 0)
                {
                    //Проверка того, что тарифное направление встречается только один раз в продукте
                    var contentProductsParametersId =
                        helper.GetSettingValue(SettingsTitles.PRODUCTS_PARAMETERS_CONTENT_ID);
                    if (parametersIds != null && parametersIds.Any())
                    {
                        var parameters = helper.GetParameters(articleService, contentProductsParametersId,
                                                              parametersIds, "c.BaseParameter is not null");
                        helper.CheckTariffAreaDuplicateExist(parameters, parametersName);
                    }

                    int    contentServiceOnTariffId = 0;
                    string tariffRelationFieldName  = null;
                    bool   hasServicesOnTariff      = true;

                    try
                    {
                        contentServiceOnTariffId = helper.GetSettingValue(SettingsTitles.SERVICES_ON_TARIFF_CONTENT_ID);
                        tariffRelationFieldName  =
                            helper.GetSettingStringValue(SettingsTitles.TARIFF_RELATION_FIELD_NAME);
                    }
                    catch (ValidationException)
                    {
                        hasServicesOnTariff = false;
                    }

                    if (hasServicesOnTariff)
                    {
                        //Получение id поля Tariffs
                        var fieldService = new FieldService(helper.Customer.ConnectionString, 1);
                        var fieldId      = fieldService.List(contentServiceOnTariffId)
                                           .Where(w => w.Name.Equals(tariffRelationFieldName)).Select(s => s.Id).FirstOrDefault();
                        //Получение Id услуг из контента "Услуги на тарифах"
                        var relationsIds = articleService.GetRelatedItems(fieldId, productId, true)?
                                           .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                           .Select(int.Parse)
                                           .ToArray();
                        if (relationsIds != null && relationsIds.Any())
                        {
                            //Проверка того, что тарифное направление встречается только один раз в связи продуктов
                            helper.CheckRelationServicesProductsTariff(articleService, contentServiceOnTariffId,
                                                                       tariffRelationFieldName, relationsIds, parametersName);

                            //Проверка того, что связь между продуктами встречается единожды
                            helper.CheckRelationProductsDuplicate(articleService, Constants.FieldId,
                                                                  contentServiceOnTariffId, relationsIds);
                        }

                        var relatedIds = new List <string>();

                        //Проверка того, что сущность с другой стороны связи не в архиве
                        var productRelationsContentId = helper.GetSettingValue(SettingsTitles.PRODUCT_RELATIONS_CONTENT_ID);
                        var contentService            = new ContentService(helper.Customer.ConnectionString, 1);

                        //Получение связанных контентов
                        var contents = contentService.Read(productRelationsContentId)
                                       .AggregatedContents
                                       .Where(w => w.Fields
                                              .Count(a => a.ExactType == FieldExactTypes.O2MRelation &&
                                                     a.RelateToContentId == product.ContentId) >= 2).ToArray();
                        foreach (var con in contents)
                        {
                            //Получение полей, по которым может быть связь
                            var productField = con.Fields
                                               .Where(w => w.ExactType == FieldExactTypes.O2MRelation &&
                                                      w.RelateToContentId == product.ContentId
                                                      ).ToArray();
                            foreach (var field in productField)
                            {
                                //Получение ids связанных статей
                                var relatedArticlesId = articleService.GetRelatedItems(field.Id, productId, true)?
                                                        .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                        .Select(int.Parse)
                                                        .ToArray();

                                if (relatedArticlesId != null && relatedArticlesId.Any())
                                {
                                    var relatedArticles = articleService.List(con.Id, relatedArticlesId, true)
                                                          .Where(w => !w.Archived).Select(s => s).ToList();
                                    var relField = productField.Where(f => f.Name != field.Name).Select(s => s).First();
                                    var rel      = relatedArticles.Select(s =>
                                                                          s.FieldValues.First(f => f.Field.Name == relField.Name).Value).ToArray();
                                    if (rel.Any())
                                    {
                                        relatedIds.AddRange(rel);
                                    }
                                }
                            }
                        }

                        helper.CheckArchivedRelatedEntity(articleService, relatedIds, productId, Constants.FieldId,
                                                          helper.GetSettingValue(SettingsTitles.PRODUCTS_CONTENT_ID));
                    }
                }

                string markProductType =
                    articleService.Read(markProductId)
                    .FieldValues.FirstOrDefault(a => a.Field.Name == productTypeName)?
                    .Value;

                //Проверка, что тип маркетингового продукта и тип продукта -- сопоставимы
                if (!articleService.List(productTypesContentId, null, true).Any(x =>
                                                                                x.FieldValues.FirstOrDefault(a => a.Field.Name == Constants.FieldProductContent)?.Value ==
                                                                                typeId.ToString() &&
                                                                                x.FieldValues.FirstOrDefault(a => a.Field.Name == Constants.FieldMarkProductContent)?.Value ==
                                                                                markProductType))
                {
                    var message = new ActionTaskResultMessage()
                    {
                        ResourceClass = ValidationHelper.ResourceClass,
                        ResourceName  = nameof(RemoteValidationMessages.SameTypeProductMarketingProduct)
                    };

                    result.AddModelError(
                        helper.GetPropertyName(markProductName), helper.ToString(message)
                        );
                }
            }

            return(result);
        }
 public RemoteValidationResult Validate(RemoteValidationContext context, RemoteValidationResult result)
 {
     return(_validators.Aggregate(result, (current, validator) => validator.Validate(context, current)));
 }
        public RemoteValidationResult Validate(RemoteValidationContext context, RemoteValidationResult result)
        {
            var xmlDefinition = context.Definitions.FirstOrDefault(x => x.Alias == FieldXmlDefinition);

            if (xmlDefinition == null)
            {
                var message = new ActionTaskResultMessage()
                {
                    ResourceClass = ValidationHelper.ResourceClass,
                    ResourceName  = nameof(RemoteValidationMessages.FieldNotFound),
                    Parameters    = new object[] { FieldXmlDefinition }
                };
                result.Messages.Add(ValidationHelper.ToString(context, message));
            }

            var xaml = context.ProvideValueExact <string>(xmlDefinition);

            if (!string.IsNullOrWhiteSpace(xaml))
            {
                Content definition;
                try
                {
                    definition = (Content)XamlConfigurationParser.CreateFrom(xaml);
                }
                catch (Exception ex)
                {
                    var message = new ActionTaskResultMessage()
                    {
                        ResourceClass = ValidationHelper.ResourceClass,
                        ResourceName  = nameof(RemoteValidationMessages.NotValidXamlDefinition),
                        Parameters    = new object[] { ex.Message }
                    };
                    result.Messages.Add(ValidationHelper.ToString(context, message));
                    return(result);
                }

                var jsonDefinition = context.Definitions.FirstOrDefault(x => x.Alias == FieldJsonDefinition);
                if (jsonDefinition != null)
                {
                    using (var stream = new MemoryStream())
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            try
                            {
                                _formatter.Write(stream, definition);
                                stream.Position = 0;
                                context.SetValue(result, jsonDefinition, reader.ReadToEnd());
                            }
                            catch (Exception ex)
                            {
                                var message = new ActionTaskResultMessage()
                                {
                                    ResourceClass = ValidationHelper.ResourceClass,
                                    ResourceName  = nameof(RemoteValidationMessages.JsonDefinitionError),
                                    Parameters    = new object[] { ex.Message }
                                };
                                result.Messages.Add(ValidationHelper.ToString(context, message));
                                return(result);
                            }
                        }
                    }
                }
            }

            return(result);
        }