示例#1
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            IValidationRepository validationRepository = null;

            if (ServiceLocator.IsLocationProviderSet)
            {
                try
                {
                    validationRepository = ServiceLocator.Current.GetInstance(typeof(IValidationRepository)) as IValidationRepository;
                }
                catch (ActivationException)
                {
                    //do nothing
                }
            }

            if (validationRepository != null)
            {
                string errorMessage;
                if (!validationRepository.ValidateProfile(this, out errorMessage))
                {
                    results.Add(new ValidationResult(string.Format("Profile failed SAP validation: {0}", errorMessage), null));
                }
            }

            return(results);
        }
 public CustomersAndOrdersViewModel(IValidationRepository validationRepository, IOrderDetailsViewModel orderDetailsViewModel)
 {
     this.validationRepository = validationRepository;
     this.orderDetailsViewModel = orderDetailsViewModel;
     var customers = validationRepository.ListDocuments<Customer>();
     Customers = new BindableCollection<Customer>(customers);
 }
示例#3
0
 public ConfigurationController(IFieldTypeRepository fieldTypeRepository, IStyleRepository styleRepository,
                                IValidationRepository validationRepository)
 {
     _fieldTypeRepository  = fieldTypeRepository;
     _styleRepository      = styleRepository;
     _validationRepository = validationRepository;
 }
        public static TSource FixValue <TSource>(this IValidationRepository repository, TSource value, string valueName, Action <PathValidation <object, TSource> > init)
        {
            var factory = repository.Create((object)value);
            var path    = new PathValidation <object, TSource>(null, factory);

            init(path);

            object objValue = value;

            var context = new ValidationContext(valueName, value);
            var result  = new ValidationResult();

            foreach (var tValidator in path.Validators)
            {
                result.Load(tValidator.Validate(context, ref objValue));
            }

            result.ThrowIssues();

            context.WithUpdate = true;

            foreach (var tValidator in path.Validators)
            {
                tValidator.Validate(context, ref objValue);
            }

            return((TSource)objValue);
        }
 public NewOrderViewModel(IValidationRepository validationRepository)
 {
     this.validationRepository = validationRepository;
     var listDocuments = validationRepository.ListDocuments<Customer>();
     Customers = new BindableCollection<Customer>(listDocuments);
     if (Customers.Count > 0)
         CustomerId = Customers.First().Id;
 }
示例#6
0
        public GetLoyalityCardDiscountQueryValidator(IValidationRepository repo)
        {
            RuleFor(x => x.RfId)
            .SetValidator(new RfIdValidator(repo, 1))
            .NotEmpty();

            RuleFor(x => x.UscId)
            .SetValidator(new UscIdValidator(repo))
            .NotEmpty();
        }
        public GetGulfCardLimitQueryValidator(IValidationRepository repo)
        {
            RuleFor(x => x.RfId)
            .SetValidator(new RfIdValidator(repo, 0))
            .NotEmpty();

            RuleFor(x => x.UscId)
            .SetValidator(new UscIdValidator(repo))
            .NotEmpty();
        }
示例#8
0
 protected TestBase()
 {
     _validationRepository          = Substitute.For <IValidationRepository>();
     _identifyXmlElementsService    = new IdentifyXmlElementsService();
     _containsXmlElementsValidator  = new ContainsXmlElementsValidator(_identifyXmlElementsService);
     _noMissingXmlElementsValidator = new NoMissingXmlElementsValidator(_identifyXmlElementsService);
     _validXmlElementsValidator     = new ValidXmlElementsValidator(_identifyXmlElementsService);
     _mandatoryXmlElementsValidator = new MandatoryXmlElementsValidator(_identifyXmlElementsService, _validationRepository);
     _xmlValidationFactory          = new XmlValidationFactory(_identifyXmlElementsService, _validationRepository);
     _xmlDeserializerService        = new XmlDeserializerService();
     _expenseService = new ExpenseService(_xmlValidationFactory, _identifyXmlElementsService, _xmlDeserializerService);
 }
        public GulfClubTransactionCommandValidator(IValidationRepository repo)
        {
            //RuleFor(x => x.Id)
            //    .SetValidator(new TransactionIdValidator(repo))
            //    .GreaterThan(0);

            RuleFor(x => x.TxnId)
            .NotNull()
            .GreaterThan(0);

            RuleFor(x => x.RfId)
            .SetValidator(new RfIdValidator(repo, 0))
            .NotEmpty();
        }
示例#10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlValidationFactory"/> class.
        /// </summary>
        /// <param name="identifyXmlElementsService">The identify XML elements service.</param>
        /// <param name="validationRepository">The validation repository.</param>
        /// <exception cref="ArgumentNullException">
        /// identifyXmlElementsService
        /// or
        /// validationRepository
        /// </exception>
        public XmlValidationFactory(IIdentifyXmlElementsService identifyXmlElementsService, IValidationRepository validationRepository)
        {
            if (identifyXmlElementsService == null)
            {
                throw new ArgumentNullException(nameof(identifyXmlElementsService));
            }
            if (validationRepository == null)
            {
                throw new ArgumentNullException(nameof(validationRepository));
            }

            _identifyXmlElementsService = identifyXmlElementsService;
            _validationRepository       = validationRepository;
        }
        public ReserveCulfCardLimitCommandValidator(IValidationRepository repo)
        {
            RuleFor(x => x.UscId)
            .SetValidator(new UscIdValidator(repo))
            .NotEmpty();

            RuleFor(x => x.RfId)
            .SetValidator(new RfIdValidator(repo, 0))
            .NotEmpty();

            RuleFor(x => x.FuelId)
            .SetValidator(new FuelIdValidator(repo))
            .GreaterThan(0);
        }
 public UscIdValidator(IValidationRepository repository) : base("UscId is not valid")
 {
     _repository = repository;
 }
示例#13
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            IValidationRepository validationRepository = null;
            IFeatureConfiguration featureConfig        = null;

            if (ServiceLocator.IsLocationProviderSet)
            {
                try
                {
                    validationRepository = ServiceLocator.Current.GetInstance(typeof(IValidationRepository)) as IValidationRepository;
                    featureConfig        = ServiceLocator.Current.GetInstance(typeof(IFeatureConfiguration)) as IFeatureConfiguration;
                }
                catch (ActivationException)
                {
                    //do nothing
                }
            }

            if (validationRepository != null)
            {
                string errorMessage;
                if (!validationRepository.ValidateProfile(this, out errorMessage))
                {
                    results.Add(new ValidationResult(string.Format("Profile failed SAP validation: {0}", errorMessage), null));
                }
            }

            #region F25195 - Add additional CCI Lines
            if (featureConfig != null)
            {
                if (featureConfig.IsAvailable(FeaturesEnum.AddRemainingCCILines))
                {
                    #region BillLaterandStandingOrdersOnly
                    if (BillLaterAndStandingOrdersOnly == true && (AllowStandingOrders == false || AllowBillLaterOrders == false))
                    {
                        results.Add(new ValidationResult("Allow Standing Orders and Allow Bill Later Orders must both be Yes.", new[] { "BillLaterandStandingOrdersOnly" }));
                    }
                    #endregion

                    #region SpecialInvoiceDate
                    if (!SpecialInvoiceDate.HasValue && UseSpecialInvoiceDateUntil.HasValue)
                    {
                        results.Add(new ValidationResult("Cannot add Use Special Invoice Date.", new[] { "SpecialInvoiceDate" }));
                    }
                    #endregion

                    #region CommonExpire
                    if (string.IsNullOrWhiteSpace(CommonExpire) || CommonExpire == "No")
                    {
                        if (AllowLongTermsAndDoubleEntries == true)
                        {
                            results.Add(new ValidationResult("Cannot add Allow Long Terms and Double Entries.", new[] { "AllowLongTermsandDoubleEntries" }));
                        }
                        if (AllowDoubleEntries == true)
                        {
                            results.Add(new ValidationResult("Cannot add Allow Double Entries.", new[] { "AllowDoubleEntries" }));
                        }
                        if (AllowLongTerms == true)
                        {
                            results.Add(new ValidationResult("Cannot add Allow Long Terms.", new[] { "AllowLongTerms" }));
                        }
                        if (AllowShortTerms == true)
                        {
                            results.Add(new ValidationResult("Cannot add Allow Short Terms.", new[] { "AllowShortTerms" }));
                        }
                    }
                    #endregion
                }
            }
            #endregion

            #region CombinePurchaseOrdersComments
            if (!string.IsNullOrWhiteSpace(CombinePurchaseOrdersComments) && (CombinePurchaseOrders))
            {
                results.Add(new ValidationResult("Cannot add Combine Purchase Orders Comments.", new[] { "CombinePurchaseOrdersComments" }));
            }
            #endregion

            #region HasBadDebtComments
            if (!string.IsNullOrWhiteSpace(HasBadDebtComments) && !(HasBadDebt))
            {
                results.Add(new ValidationResult("Cannot add Has Bad Debt Comments.", new[] { "HasBadDebtComments" }));
            }
            #endregion

            #region OrderCannotExceedAmountOnPurchaseOrderByAmount && OrderCannotExceedAmountOnPurchaseOrderByPercent
            if ((OrderCannotExceedAmountOnPurchaseOrderByAmount.HasValue) && (OrderCannotExceedAmountOnPurchaseOrderByPercent.HasValue))
            {
                results.Add(new ValidationResult("Order Cannot Exceed Amount On Purchase Order By must be either an amount or a percentage.", new[] { "OrderCannotExceedAmountOnPurchaseOrderByAmountComments" }));
            }
            #endregion

            #region OrderCannotExceedAmountOnPurchaseOrderByPercentComments
            if (!string.IsNullOrWhiteSpace(OrderCannotExceedAmountOnPurchaseOrderByPercentComments) && !(OrderCannotExceedAmountOnPurchaseOrderByPercent.HasValue))
            {
                results.Add(new ValidationResult("Cannot add Order Cannot Exceed Amount On Purchase Order By (Percent) Comments.", new[] { "OrderCannotExceedPercentOnPurchaseOrderByPercentComments" }));
            }
            #endregion

            #region OrderCannotExceedAmountOnPurchaseOrderByAmountComments
            if (!string.IsNullOrWhiteSpace(OrderCannotExceedAmountOnPurchaseOrderByAmountComments) && !(OrderCannotExceedAmountOnPurchaseOrderByAmount.HasValue))
            {
                results.Add(new ValidationResult("Cannot add Order Cannot Exceed Amount On Purchase Order By (Amount) Comments.", new[] { "OrderCannotExceedAmountOnPurchaseOrderByAmountComments" }));
            }
            #endregion

            #region PaymentRequiredBeforeProcessingComments
            if (!string.IsNullOrWhiteSpace(PaymentRequiredBeforeProcessingComments) && !(PaymentRequiredBeforeProcessing))
            {
                results.Add(new ValidationResult("Cannot add Payment Required Before Processing Comments.", new[] { "PaymentRequiredBeforeProcessingComments" }));
            }
            #endregion

            #region ProcessWithoutFormalPurchaseOrderComments
            if (!string.IsNullOrWhiteSpace(ProcessWithoutFormalPurchaseOrderComments) && (ProcessWithoutFormalPurchaseOrder))
            {
                results.Add(new ValidationResult("Cannot add Process Without Formal Purchase Order Comments.", new[] { "ProcessWithoutFormalPurchaseOrderComments" }));
            }
            #endregion

            #region PurchaseOrderNumberComments
            if (!string.IsNullOrWhiteSpace(PurchaseOrderNumberComments) && string.IsNullOrWhiteSpace(PurchaseOrderNumber))
            {
                results.Add(new ValidationResult("Cannot add Purchase Order Number Comments.", new[] { "PurchaseOrderNumberComments" }));
            }
            #endregion

            #region PurchaseOrderNumberSatisfiesFormalRequirementComments
            if (!string.IsNullOrWhiteSpace(PurchaseOrderNumberSatisfiesFormalRequirementComments) && !(PurchaseOrderNumberSatisfiesFormalRequirement))
            {
                results.Add(new ValidationResult("Cannot add Purchase Order Number Satisfies Formal Requirement Comments.", new[] { "PurchaseOrderNumberSatisfiesFormalRequirementComments" }));
            }
            #endregion

            #region EditRequiredBeforeProcessingComments
            if (!string.IsNullOrWhiteSpace(EditRequiredBeforeProcessingComments) && !(EditRequiredBeforeProcessing))
            {
                results.Add(new ValidationResult("Cannot add Edit Required Before Processing Comments.", new[] { "EditRequiredBeforeProcessingComments" }));
            }
            #endregion

            if (featureConfig != null)
            {
                if (featureConfig.IsAvailable(FeaturesEnum.CcisAddedToOrdersProfile))
                {
                    #region NumberOfUsers

                    if (string.IsNullOrWhiteSpace(NumberOfUsersWithOnlineJournalAccess.ToString()) &&
                        !string.IsNullOrWhiteSpace(NumberOfUsersWithOnlineJournalAccessComments))
                    {
                        results.Add(new ValidationResult("Number Of Users with Online Journal Access is not provided.",
                                                         new[] { "NumberOfUsersWithOnlineJournalAccess." }));
                    }

                    #endregion

                    #region AccessToOffers

                    if (string.IsNullOrEmpty(AccessToOffersForFreeOnlineJournals))
                    {
                        results.Add(new ValidationResult(" Access to Offers is not provided",
                                                         new[] { "AccessToOffersForFreeOnlineJournals" }));
                    }
                }

                #endregion
            }



            return(results);
        }
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            IValidationRepository validationRepository = null;
            IFeatureConfiguration featureConfig        = null;

            if (ServiceLocator.IsLocationProviderSet)
            {
                try
                {
                    validationRepository = ServiceLocator.Current.GetInstance(typeof(IValidationRepository)) as IValidationRepository;
                    featureConfig        = ServiceLocator.Current.GetInstance(typeof(IFeatureConfiguration)) as IFeatureConfiguration;
                }
                catch (ActivationException)
                {
                    //do nothing
                }
            }

            #region BreakAdjustmentsBySubscriber
            if (BreakAdjustmentsbySubscriber && (OriginalInvoiceItemCount > 0 || SupplementalInvoiceItemCount > 0))
            {
                results.Add(new ValidationResult("Cannot break Adjustments by Subscriber.", new[] { "BreakAdjustmentsbySubscriber" }));
            }

            #endregion

            if (string.IsNullOrEmpty(EmailAddressToSendAdjustments) &&
                (EmailAlphaCopyOnly || EmailOriginalAndSupplementalInvoices || EmailOriginalInvoicesOnly || EmailSpecialSortCopyOnly))
            {
                results.Add(new ValidationResult("Email Address for Adjustments is not provided.", new[] { "EmailAddressToSendAdjustments" }));
            }

            #region IssueRefundbyCheckNoCredits
            if (featureConfig != null)
            {
                if (featureConfig.IsAvailable(FeaturesEnum.AddRemainingCCILines))
                {
                    if ((IssueRefundByCheckNoCredits == false) && !string.IsNullOrWhiteSpace(IssueRefundByCheckNoCreditsComments))
                    {
                        results.Add(new ValidationResult("Cannot add Issue Refund by Check - No Credits Comments.", new[] { "IssueRefundbyCheckNoCreditsComments" }));
                    }
                }
            }
            #endregion

            if (validationRepository != null)
            {
                string errorMessage;
                if (!validationRepository.ValidateProfile(this, out errorMessage))
                {
                    results.Add(new ValidationResult(string.Format("Profile failed SAP validation: {0}", errorMessage), null));
                }
            }

            if (!(AdjustmentBillingMonths.HasFlag(MonthEnumFlag.January) ||
                  AdjustmentBillingMonths.HasFlag(MonthEnumFlag.February) ||
                  AdjustmentBillingMonths.HasFlag(MonthEnumFlag.March) ||
                  AdjustmentBillingMonths.HasFlag(MonthEnumFlag.April) ||
                  AdjustmentBillingMonths.HasFlag(MonthEnumFlag.May) ||
                  AdjustmentBillingMonths.HasFlag(MonthEnumFlag.June) ||
                  AdjustmentBillingMonths.HasFlag(MonthEnumFlag.July) ||
                  AdjustmentBillingMonths.HasFlag(MonthEnumFlag.August) ||
                  AdjustmentBillingMonths.HasFlag(MonthEnumFlag.September) ||
                  AdjustmentBillingMonths.HasFlag(MonthEnumFlag.October) ||
                  AdjustmentBillingMonths.HasFlag(MonthEnumFlag.November) ||
                  AdjustmentBillingMonths.HasFlag(MonthEnumFlag.December)
                  ))
            {
                results.Add(new ValidationResult("Adjustment Billing Months is required", null));
            }


            return(results);
        }
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            IRepository           repository           = null;
            IValidationRepository validationRepository = null;
            IFeatureConfiguration featureConfig        = null;

            if (ServiceLocator.IsLocationProviderSet)
            {
                try
                {
                    repository           = ServiceLocator.Current.GetInstance(typeof(IRepository)) as IRepository;
                    validationRepository = ServiceLocator.Current.GetInstance(typeof(IValidationRepository)) as IValidationRepository;
                    featureConfig        = ServiceLocator.Current.GetInstance(typeof(IFeatureConfiguration)) as IFeatureConfiguration;
                }
                catch (ActivationException)
                {
                    //do nothing
                }
            }


            IEnumerable <SecondaryCustomerProfile> secondaryProfiles  = null;
            IEnumerable <ShippingLocation>         ActiveZZSubscriber = null;

            if (repository != null)
            {
                var suffixLegacyMappingIds = LegacyMappings.Where(lm => lm.LegacySystemName == LegacySystemNames.Suffix.Name).Select(x => x.Id);

                secondaryProfiles = repository.GetCustomer(CustomerId, RelatedEntitiesEnum.SecondaryCustomerProfiles)
                                    .SecondaryCustomerProfiles
                                    .Where(scp => scp.LegacyMappings.Any(pplm => suffixLegacyMappingIds.Contains(pplm.Id)));

                ActiveZZSubscriber = repository.GetCustomer(CustomerId, RelatedEntitiesEnum.ShippingLocations)
                                     .ShippingLocations.Where(x => x.LegacyMappings.Exists(lm => lm.LegacySystemName == LegacySystemNames.Subscriber.Name && lm.LegacyIdentifier.Substring(8, 2) == "ZZ") && x.IsActive)
                                     .ToList();
            }

            if (UsesEbsconetForRenewals)
            {
                if (secondaryProfiles != null)
                {
                    if (secondaryProfiles.Any(x => x.EBSCONetCustomer == false))
                    {
                        results.Add(new ValidationResult("Cannot use EBSCONET for Renewals if Customer is not set up for EBSCONET", new[] { "EBSCONetCustomer" }));
                    }
                }
            }

            if (validationRepository != null)
            {
                string errorMessage;
                if (!validationRepository.ValidateProfile(this, out errorMessage))
                {
                    results.Add(new ValidationResult(string.Format("Profile failed SAP validation: {0}", errorMessage), null));
                }
            }
            #region F17008;
            if (featureConfig != null)
            {
                var CcisAddedToRenewalsProfileFeatureEnabled = featureConfig.IsAvailable(FeaturesEnum.CcisAddedToRenewalsProfile);

                if (CcisAddedToRenewalsProfileFeatureEnabled)
                {
                    if (!String.IsNullOrEmpty(MailRenewalsToComments) && String.IsNullOrEmpty(MailRenewalsTo))
                    {
                        results.Add(new ValidationResult("Mail Renewals To is not selected.", new[] { "MailRenewalsTo" }));
                    }

                    if (!String.IsNullOrEmpty(MailRenewalsToComments) && MailRenewalsToComments.Length > 500)
                    {
                        results.Add(new ValidationResult("Mail Renewals To Comments length cannot be greater than 500."));
                    }


                    if (!String.IsNullOrEmpty(PaymentDocumentHeading) && PaymentDocumentHeading.Length > 30)
                    {
                        results.Add(new ValidationResult("Payment Document Heading length cannot be greater than 30."));
                    }


                    if (!String.IsNullOrEmpty(PaymentDocumentHeading) && ProduceRenewalAsAPaymentDocument == false)
                    {
                        results.Add(new ValidationResult("Heading is not valid if Renewal is not set up as Payment Document."));
                    }



                    //   if (UsesEbsconetEpackageRenewals == true && UsesEbsconetForRenewals == true)
                    //    results.Add(new ValidationResult("EBSCONET ePackage Renewals (EPR) and EBSCONET Renewals are mutually exclusive."));


                    if (UsesEbsconetEpackageRenewals)
                    {
                        if (secondaryProfiles != null)
                        {
                            if (secondaryProfiles.Any(x => x.EBSCONetCustomer == false))
                            {
                                results.Add(new ValidationResult("Cannot use EBSCONET ePackage Renewals (EPR) if Customer is not set up for EBSCONET.", new[] { "EBSCONetCustomer" }));
                            }
                        }
                    }
                    // if (MailRenewalsTo == "ZZ Subscriber" && shippingLocation != shippingLocation.Where(x => x.LegacyMappings.First(lm => lm.LegacySystemName == LegacySystemName.Subscriber).LegacyIdentifier.Reverse().ToString().Substring(0, 2).ToLower().Equals("zz") && x.IsActive))

                    //  results.Add(new ValidationResult("Subscriber Code ZZ is not active.", new[] { "MailRenewalsTo" }));
                    if (MailRenewalsTo == "ZZ Subscriber" && ActiveZZSubscriber.Count() == 0)
                    {
                        results.Add(new ValidationResult("Subscriber Code ZZ is not active.", new[] { "MailRenewalsTo" }));
                    }
                }
                #endregion
            }
            return(results);
        }
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            #region ILSRequiredComments
            if (!string.IsNullOrWhiteSpace(ILSRequiredComments) && !(ILSRequired))
            {
                results.Add(new ValidationResult("Comments cannot be entered unless ILS Required is Yes.", new[] { "ILSRequiredComments" }));
            }
            #endregion

            #region IntegrateWithOrderAPI
            if ((IntegrateWithOrderAPI) && (ILSSystem != "ALMA"))
            {
                results.Add(new ValidationResult("Can only integrate with Orders API if ILS System is ALMA.", new[] { "IntegrateWithOrderAPI" }));
            }
            #endregion

            #region ILSPasscode
            if (string.IsNullOrWhiteSpace(ILSPasscode) && (IntegrateWithOrderAPI))
            {
                results.Add(new ValidationResult("ILS Passcode is required in order to integrate with order API.", new[] { "ILSPasscode" }));
            }
            #endregion

            #region ILSOwner
            if (string.IsNullOrWhiteSpace(ILSOwner) && (IntegrateWithOrderAPI))
            {
                results.Add(new ValidationResult("ILS Owner is required in order to integrate with order API.", new[] { "ILSOwner" }));
            }
            #endregion

            #region ILSVendor
            if (string.IsNullOrWhiteSpace(VendorCode) && (IntegrateWithOrderAPI))
            {
                results.Add(new ValidationResult("Vendor Code is required in order to Integrate with Orders API.", new[] { "ILSVendor" }));
            }
            #endregion

            #region ILSVendorAccount
            if (string.IsNullOrWhiteSpace(CustomerCode) && (IntegrateWithOrderAPI))
            {
                results.Add(new ValidationResult("Customer Code is required in order to Integrate with Orders API.", new[] { "ILSVendorAccount" }));
            }
            #endregion

            IValidationRepository validationRepository = null;
            if (ServiceLocator.IsLocationProviderSet)
            {
                try
                {
                    validationRepository = ServiceLocator.Current.GetInstance(typeof(IValidationRepository)) as IValidationRepository;
                }
                catch (ActivationException)
                {
                    //do nothing
                }
            }

            if (validationRepository != null)
            {
                string errorMessage;
                if (!validationRepository.ValidateProfile(this, out errorMessage))
                {
                    results.Add(new ValidationResult(string.Format("Profile failed SAP validation: {0}", errorMessage), null));
                }
            }


            return(results);
        }
 public NewCustomerViewModel(IValidationRepository validationRepository)
 {
     this.validationRepository = validationRepository;
 }
 public void PrepareDetails(IValidationRepository validationRepository, Guid id)
 {
     var customer = validationRepository.LoadDocument<Customer>(id);
     Orders = new BindableCollection<Order>(customer.Orders);
     DisplayName = customer.Name;
 }
示例#19
0
 public SettingsAuthenticatonProvider(IValidationRepository repository)
 {
     this.repository = repository;
 }
示例#20
0
 public ValidationRuleFactory(IValidationRepository repository, object originalValue)
 {
     Repository    = repository;
     OriginalValue = originalValue;
 }
        public static TSource Fix <TSource>(this IValidationRepository repository, TSource source, Action <ValidationRuleFactory <TSource> > init)
        {
            var factory = repository.Create(source, init);

            return(factory.Fix(source));
        }
示例#22
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            Regex expr = new Regex(@"([0-9])+");

            var results = new List <ValidationResult>();

            if (!string.IsNullOrWhiteSpace(FirstName))
            {
                if (expr.Match(FirstName).Success)
                {
                    results.Add(new ValidationResult("First Name cannot contain numerals."));
                }
            }

            if (!string.IsNullOrWhiteSpace(MiddleName))
            {
                if (expr.Match(MiddleName).Success)
                {
                    results.Add(new ValidationResult("Middle Name cannot contain numerals."));
                }
            }

            if (!string.IsNullOrWhiteSpace(LastName))
            {
                if (expr.Match(LastName).Success)
                {
                    results.Add(new ValidationResult("Last Name cannot contain numerals."));
                }
            }

            foreach (var email in EmailAddresses)
            {
                Validator.TryValidateObject(email,
                                            new ValidationContext(email, null, null),
                                            results,
                                            true);
            }

            foreach (var phone in PhoneNumbers)
            {
                Validator.TryValidateObject(phone,
                                            new ValidationContext(phone, null, null),
                                            results,
                                            true);
            }

            IValidationRepository validationRepository = null;

            if (ServiceLocator.IsLocationProviderSet)
            {
                try
                {
                    validationRepository = ServiceLocator.Current.GetInstance(typeof(IValidationRepository)) as IValidationRepository;
                }
                catch (ActivationException)
                {
                    //do nothing
                }
            }

            if (validationRepository != null)
            {
                string errorMessage;
                if (!validationRepository.ValidateContact(this, out errorMessage))
                {
                    results.Add(new ValidationResult(string.Format("Account failed SAP validation: {0}", errorMessage), null));
                }
            }

            return(results);
        }
示例#23
0
 public SettingsAuthorizationProvider(IValidationRepository repository)
 {
     this.repository    = repository;
     this.authenticator = new SettingsAuthenticatonProvider(repository);
 }
 public ValidationController(IValidationRepository validationRepository)
 {
     _validationRepository = validationRepository;
 }
示例#25
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            var officeCodes = LegacyMappings.Where(x => x.LegacySystemName == LegacySystemNames.Account.Name).Select(x => x.LegacyIdentifier.Substring(0, 2)).Distinct();

            IRepository           repository           = null;
            IValidationRepository validationRepository = null;
            IFeatureConfiguration featureConfig        = null;

            if (ServiceLocator.IsLocationProviderSet)
            {
                try
                {
                    repository           = ServiceLocator.Current.GetInstance(typeof(IRepository)) as IRepository;
                    validationRepository = ServiceLocator.Current.GetInstance(typeof(IValidationRepository)) as IValidationRepository;
                    featureConfig        = ServiceLocator.Current.GetInstance(typeof(IFeatureConfiguration)) as IFeatureConfiguration;
                }
                catch (ActivationException)
                {
                    //do nothing
                }
            }

            if (repository != null)
            {
                if (Id > 0)
                {
                    var existingProfile = repository.GetSecondaryCustomerProfile(Id);
                    if (existingProfile != null && !string.IsNullOrEmpty(existingProfile.ISOBillingCurrency.Trim()) && existingProfile.ISOBillingCurrency != ISOBillingCurrency)
                    {
                        results.Add(new ValidationResult("ISO Billing Currency cannot be changed.", new[] { "ISOBillingCurrency" }));
                    }
                }
            }



            //verify EBSCOBillingCurrency is populated
            if (new[] { "AU", "BA", "FB", "JA", "KO", "MX", "NZ", "TO", "TQ", "TW", "ZE", "ZI", "ZJ", "ZN", "ZP", "ZQ", "ZR", "ZS", "ZT", "ZU", "ZV", "ZX", "ZZ", "ZF", "ZY" }.Any(o1 => officeCodes.Any(o2 => o1 == o2)))
            {
                if (string.IsNullOrWhiteSpace(EBSCOBillingCurrency))
                {
                    results.Add(new ValidationResult("EBSCO Billing Currency is required.", new[] { "EBSCOBillingCurrency" }));
                }
            }

            //verify EBSCOBillingCurrency is populated
            //if (new[] { "BR", "BT", "CG", "DC", "DV", "LA", "RB", "SF", "TN" }.Any(o1 => officeCodes.Any(o2 => o1 == o2)))
            //    if (!string.IsNullOrWhiteSpace(EBSCOBillingCurrency) && !StringComparer.OrdinalIgnoreCase.Equals(EBSCOBillingCurrency, "US"))
            //        results.Add(new ValidationResult("EBSCO Billing Currency must be 'US'.", new[] { "EBSCOBillingCurrency" }));

            //verify arcurrency is valid for given EBSCOBillingCurrency
            if (EBSCOBillingCurrency != null && EBSCOBillingCurrency == "US" && ARCurrency != "US")
            {
                results.Add(new ValidationResult("A/R Currency is not a valid selection", new[] { "ARCurrency" }));
            }

            //verify satellite office code and satellite country is not blank for certain offices
            if (new[] { "ZU", "ZA", "ZJ", "ZN", "ZQ", "ZS", "ZT", "ZZ", "ZE", "ZX", "ZR", "ZC", "ZI", "ZP", "ZV", "ZF", "ZY", "AU", "NZ", "BA", "FB", "JA", "KO", "MX", "TW" }.Any(o1 => officeCodes.Any(o2 => o1 == o2)))
            {
                if (string.IsNullOrWhiteSpace(SatelliteOfficeCode))
                {
                    results.Add(new ValidationResult("Satellite Office Code is required.", new[] { "SatelliteOfficeCode" }));
                }
                if (string.IsNullOrWhiteSpace(SatelliteCountry))
                {
                    results.Add(new ValidationResult("Satellite Country is required.", new[] { "SatelliteCountry" }));
                }
            }


            if (new[] { "TO", "TQ" }.Any(o1 => officeCodes.Any(o2 => o1 == o2)) && (ISOBillingCurrency ?? string.Empty) == "USD")
            {
                if (!StringComparer.OrdinalIgnoreCase.Equals(SatelliteOfficeCode, "USA"))
                {
                    results.Add(new ValidationResult("Satellite Office Code must be selected.", new[] { "SatelliteOfficeCode" }));
                }
                if (officeCodes.Count() > 1 || !StringComparer.OrdinalIgnoreCase.Equals(officeCodes.First(), SatelliteCountry))
                {
                    results.Add(new ValidationResult("Satellite Country must equal the Office Code.", new[] { "SatelliteCountry" }));
                }
            }


            //verify satellite office code and satellite country are populated only for certain offices
            if (officeCodes.Any(o1 => !new[] { "ZU", "ZA", "ZJ", "ZN", "ZQ", "ZS", "ZT", "ZZ", "ZE", "ZX", "ZR", "ZC", "ZI", "ZP", "ZV", "ZF", "ZY", "AU", "NZ", "BA", "FB", "JA", "KO", "MX", "TW", "TO", "TQ" }.Any(o2 => o1 == o2)))
            {
                if (!string.IsNullOrWhiteSpace(SatelliteOfficeCode))
                {
                    results.Add(new ValidationResult("Satellite Office Code is not available.", new[] { "SatelliteOfficeCode" }));
                }
                if (!string.IsNullOrWhiteSpace(SatelliteCountry))
                {
                    results.Add(new ValidationResult("Satellite Country is not available.", new[] { "SatelliteCountry" }));
                }
            }

            if ((!string.IsNullOrWhiteSpace(SatelliteOfficeCode) && string.IsNullOrWhiteSpace(SatelliteCountry)) ||
                (string.IsNullOrWhiteSpace(SatelliteOfficeCode) && !string.IsNullOrWhiteSpace(SatelliteCountry)))
            {
                results.Add(new ValidationResult("Satellite Office Code and Satellite Country must both be provided."));
            }


            if (!string.IsNullOrWhiteSpace(EBSCONetCustomerComments) && EBSCONetCustomer == false)
            {
                results.Add(new ValidationResult("EBSCONET Customer Comments cannot be entered.", new[] { "EBSCONetCustomerComments" }));
            }

            if (validationRepository != null)
            {
                string errorMessage;
                if (!validationRepository.ValidateProfile(this, out errorMessage))
                {
                    results.Add(new ValidationResult(string.Format("Profile failed SAP validation: {0}", errorMessage), null));
                }
            }

            //verify ebsco billing currency belongs to iso billing currency
            if (validationRepository != null)
            {
                if (!string.IsNullOrEmpty(ISOBillingCurrency) && !string.IsNullOrEmpty(EBSCOBillingCurrency))
                {
                    string errorMessage;
                    if (!validationRepository.HasMatchingEbscoAndISOCurrencies(ISOBillingCurrency, EBSCOBillingCurrency, out errorMessage))
                    {
                        results.Add(new ValidationResult(errorMessage));
                    }
                }
            }

            if (!IncludeInNetPublishersLogic.HasValue)
            {
                IncludeInNetPublishersLogic = true;
            }

            if (!EmailCSRForEJournalUpdates.HasValue)
            {
                EmailCSRForEJournalUpdates = true;
            }

            if (string.IsNullOrWhiteSpace(EJSCustomer))
            {
                EJSCustomer = "No";
            }

            if (featureConfig != null)
            {
                if (featureConfig.IsAvailable(FeaturesEnum.AddRemainingCCILines))
                {
                    //Verify Ingenta ID Comments cannot be entered if Ingenta ID is null
                    if (!string.IsNullOrWhiteSpace(IngentaIDComments) && string.IsNullOrWhiteSpace(IngentaID))
                    {
                        results.Add(new ValidationResult("Ingenta ID Comments cannot be entered.", new[] { "IngentaIDComments" }));
                    }

                    //Verify Athens ID Comments cannot be entered if Athens ID is null
                    if (!string.IsNullOrWhiteSpace(AthensIDComments) && string.IsNullOrWhiteSpace(AthensID))
                    {
                        results.Add(new ValidationResult("Athens ID Comments cannot be entered.", new[] { "AthensIDComments" }));
                    }
                }
            }

            return(results);
        }
示例#26
0
 public ValidationsController(IValidationRepository ValidationRepository)
 {
     _ValidationRepository = ValidationRepository;
 }
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            if ((new[] { "US", "CA" }.Contains(CountryCode)) && string.IsNullOrWhiteSpace(PostalCode))
            {
                results.Add(new ValidationResult("Postal is required.", new[] { "Postal" }));
            }

            if (CountryCode == "US" && PostalCode != null && !Regex.Match(PostalCode, @"^\d{1,5}(\-\d{4})?$").Success)
            {
                results.Add(new ValidationResult("Postal is not valid.", new[] { "Postal" }));
            }

            if ((new[] { "US", "CA", "AU" }.Contains(CountryCode)) && string.IsNullOrWhiteSpace(StateProvince))
            {
                results.Add(new ValidationResult("State is required.", new[] { "StateProvince" }));
            }

            if (CountryCode == "CA" && PostalCode != null && !Regex.Match(PostalCode, @"(\D\d\D\s\d\D\d)").Success)
            {
                results.Add(new ValidationResult("Postal is not valid.", new[] { "Postal" }));
            }

            if (MainframeAddressOverride != null)
            {
                if (string.IsNullOrWhiteSpace(MainframeAddressOverride.PostalCode) && (MainframeAddressOverride.CountryCode == "US"))
                {
                    results.Add(new ValidationResult("ZIP is required.", new[] { "Postal" }));
                }

                if (!string.IsNullOrWhiteSpace(MainframeAddressOverride.PostalCode) && !(MainframeAddressOverride.CountryCode == "US"))
                {
                    results.Add(new ValidationResult("ZIP is for US only.", new[] { "Postal" }));
                }
            }


            var accountLegacyMapping = LegacyMappings.FirstOrDefault(x => x.LegacySystemName == LegacySystemNames.Account.Name);

            if (accountLegacyMapping != null && BillingProfile != null)
            {
                if (accountLegacyMapping.LegacyIdentifier.StartsWith("Z") && BillingProfile.TaxExemptNumber != null)
                {
                    results.Add(new ValidationResult("Tax Exempt Number cannot be used for this office."));
                }

                //VAT Number  Office != Z * Value is not null   VAT Number cannot be used for this office.
                if (BillingProfile.VATNumber != null && !accountLegacyMapping.LegacyIdentifier.StartsWith("Z"))
                {
                    results.Add(new ValidationResult("VAT Number cannot be used for this office.", new[] { "VATNumber" }));
                }
            }

            //GST Exempt  Billing Address Country != Canada  Value = Y   Country cannot be GST Exempt.
            if (BillingProfile.GSTExempt == true && CountryCode != "CA")
            {
                results.Add(new ValidationResult("Country cannot be GST Exempt."));
            }


            //QST Exempt  Billing Address Country != Canada  Value = Y   Country cannot be QST Exempt.
            if (BillingProfile.QSTExempt == true && CountryCode != "CA")
            {
                results.Add(new ValidationResult("Country cannot be QST Exempt."));
            }



            if (results.Count > 0)
            {
                return(results);
            }


            IValidationRepository validator  = null;
            IRepository           repository = null;

            try
            {
                if (ServiceLocator.IsLocationProviderSet)
                {
                    try
                    {
                        validator  = ServiceLocator.Current.GetInstance <IValidationRepository>();
                        repository = ServiceLocator.Current.GetInstance(typeof(IRepository)) as IRepository;
                    }
                    catch (ActivationException) { }
                }

                /* validate the address using the tax service */
                if (validator != null)
                {
                    if (!validator.ValidateTaxAddress(this))
                    {
                        results.Add(new ValidationResult("Billing Address is not tax compliant.  City and/or Postal Code are invalid for the selected Country.", new[] { "SystemAddress" }));
                    }

                    string errorMessage;
                    if (!validator.ValidateBillingLocation(this, out errorMessage))
                    {
                        results.Add(new ValidationResult(string.Format("Billing location failed SAP validation: {0}", errorMessage), null));
                    }
                }


                if (LegacyMappings.Any(x => x.LegacySystemName == LegacySystemNames.Suffix.Name))
                {
                    if (MainframeAddressOverride == null)
                    {
                        if (repository != null)
                        {
                            var formatter        = new MainframeAddressFormatter(repository);
                            var convertedAddress = formatter.ConvertBillingAddress(this);
                            if (
                                (convertedAddress.Name ?? string.Empty).Length > 30 ||
                                (convertedAddress.Line1 ?? string.Empty).Length > 30 ||
                                (convertedAddress.Line2 ?? string.Empty).Length > 30 ||
                                (convertedAddress.Line3 ?? string.Empty).Length > 30
                                )
                            {
                                results.Add(new ValidationResult("Billing Address is not mainframe compliant. Please use Mainframe Override address."));
                            }
                        }
                    }
                    else
                    {
                        /* Check if the billing address is mainframe compliant and still mainframe override address is provided  */
                        if (repository != null)
                        {
                            var formatter        = new MainframeAddressFormatter(repository);
                            var convertedAddress = formatter.ConvertBillingAddress(this);
                            if (
                                (convertedAddress.Name ?? string.Empty).Length <= 30 &&
                                (convertedAddress.Line1 ?? string.Empty).Length <= 30 &&
                                (convertedAddress.Line2 ?? string.Empty).Length <= 30 &&
                                (convertedAddress.Line3 ?? string.Empty).Length <= 30
                                )
                            {
                                results.Add(new ValidationResult(
                                                "Billing Address is mainframe compliant. Please remove Mainframe Override address."));
                                return(results);
                            }
                        }

                        var context = new ValidationContext(MainframeAddressOverride, serviceProvider: null, items: null);
                        Validator.TryValidateObject(MainframeAddressOverride, context, results, true);
                    }

                    if (BillingProfile != null)
                    {
                        var context = new ValidationContext(BillingProfile, serviceProvider: null, items: null);
                        Validator.TryValidateObject(BillingProfile, context, results, true);
                    }


                    if (repository == null)
                    {
                        return(results);
                    }

                    if (accountLegacyMapping == null)
                    {
                        return(results);
                    }

                    var suffixLegacyMapping = LegacyMappings.First(x => x.LegacySystemName == LegacySystemNames.Suffix.Name);

                    var countries = repository.GetCountries();
                    var country   = countries.FirstOrDefault(x => x.Value == CountryCode);
                    if (string.IsNullOrEmpty(country?.MainframeShortCode) && MainframeAddressOverride == null)
                    {
                        results.Add(new ValidationResult("Billing Address is not mainframe compliant. Mainframe does not support the specified country.  Please use Mainframe Override Address."));
                    }
                }

                return(results);
            }
            finally
            {
                validator?.Dispose();
                repository?.Dispose();
            }
        }
 public SettingsAuthorizationProvider(IValidationRepository repository)
 {
     this.repository = repository;
     this.authenticator = new SettingsAuthenticatonProvider(repository);
 }
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            IFeatureConfiguration _feature = null;

            try
            {
                _feature = ServiceLocator.Current.GetInstance(typeof(IFeatureConfiguration)) as IFeatureConfiguration;
            }
            catch (ActivationException ae)
            {
            }

            if (_feature.IsAvailable(FeaturesEnum.ManageSuffixes))
            {
                if (IsDeleted || !IsActive)
                {
                    IRepository           repository     = null;
                    IValidationRepository validationRepo = null;

                    try
                    {
                        repository     = ServiceLocator.Current.GetInstance(typeof(IRepository)) as IRepository;
                        validationRepo = ServiceLocator.Current.GetInstance(typeof(IValidationRepository)) as IValidationRepository;
                    }
                    catch (ActivationException ae)
                    {
                    }

                    if (this.LegacySystemName == LegacySystemNames.Suffix.Name)
                    {
                        if (validationRepo != null)
                        {
                            if (validationRepo.HasActiveInvoices(this))
                            {
                                results.Add(new ValidationResult("Suffix " + LegacyIdentifier + " has pending invoices and cannot be deleted or deactivated."));
                            }
                        }
                    }

                    if (repository != null)
                    {
                        var customer = repository.GetCustomer(CustomerId, RelatedEntitiesEnum.SecondaryCustomerProfiles |
                                                              RelatedEntitiesEnum.RenewalProfiles |
                                                              RelatedEntitiesEnum.OrderProfiles |
                                                              RelatedEntitiesEnum.InvoiceProfiles |
                                                              RelatedEntitiesEnum.PricingProfiles |
                                                              RelatedEntitiesEnum.IlsProfiles |
                                                              RelatedEntitiesEnum.CCICodingProfiles |
                                                              RelatedEntitiesEnum.ReportingProfiles |
                                                              RelatedEntitiesEnum.CreditsAndAdjustmentsProfiles);

                        var secondaries = customer.SecondaryCustomerProfiles.Where(x => !x.IsDefault)
                                          .Where(y => y.LegacyMappings.Any(z => z.LegacySystemName == "Mainframe - Suffix" &&
                                                                           z.LegacyIdentifier == LegacyIdentifier));

                        secondaries.ToList().ForEach(profile =>
                        {
                            if (profile.LegacyMappings.Where(mapping => mapping.LegacySystemName == "Mainframe - Suffix").ToList().Count > 1)
                            {
                                results.Add(new ValidationResult("Suffix " + LegacyIdentifier + " shares a Secondary Customer Profile with another suffix and cannot be deleted or deactivated."));
                            }
                        });

                        var renewals = customer.RenewalProfiles.Where(x => !x.IsDefault)
                                       .Where(y => y.LegacyMappings.Any(z => z.LegacySystemName == "Mainframe - Suffix" &&
                                                                        z.LegacyIdentifier == LegacyIdentifier));

                        renewals.ToList().ForEach(profile =>
                        {
                            if (profile.LegacyMappings.Where(mapping => mapping.LegacySystemName == "Mainframe - Suffix").ToList().Count > 1)
                            {
                                results.Add(new ValidationResult("Suffix " + LegacyIdentifier + " shares a Renewals Profile with another suffix and cannot be deleted or deactivated."));
                            }
                        });

                        var orders = customer.OrderProfiles.Where(x => !x.IsDefault)
                                     .Where(y => y.LegacyMappings.Any(z => z.LegacySystemName == "Mainframe - Suffix" &&
                                                                      z.LegacyIdentifier == LegacyIdentifier));

                        orders.ToList().ForEach(profile =>
                        {
                            if (profile.LegacyMappings.Where(mapping => mapping.LegacySystemName == "Mainframe - Suffix").ToList().Count > 1)
                            {
                                results.Add(new ValidationResult("Suffix " + LegacyIdentifier + " shares an Orders Profile with another suffix and cannot be deleted or deactivated."));
                            }
                        });

                        var invoices = customer.InvoiceProfiles.Where(x => !x.IsDefault)
                                       .Where(y => y.LegacyMappings.Any(z => z.LegacySystemName == "Mainframe - Suffix" &&
                                                                        z.LegacyIdentifier == LegacyIdentifier));

                        invoices.ToList().ForEach(profile =>
                        {
                            if (profile.LegacyMappings.Where(mapping => mapping.LegacySystemName == "Mainframe - Suffix").ToList().Count > 1)
                            {
                                results.Add(new ValidationResult("Suffix " + LegacyIdentifier + " shares an Invoice Profile with another suffix and cannot be deleted or deactivated."));
                            }
                        });

                        var pricing = customer.PricingProfiles.Where(x => !x.IsDefault)
                                      .Where(y => y.LegacyMappings.Any(z => z.LegacySystemName == "Mainframe - Suffix" &&
                                                                       z.LegacyIdentifier == LegacyIdentifier));

                        pricing.ToList().ForEach(profile =>
                        {
                            if (profile.LegacyMappings.Where(mapping => mapping.LegacySystemName == "Mainframe - Suffix").ToList().Count > 1)
                            {
                                results.Add(new ValidationResult("Suffix " + LegacyIdentifier + " shares a Pricing Profile with another suffix and cannot be deleted or deactivated."));
                            }
                        });

                        var ils = customer.IlsProfiles.Where(x => !x.IsDefault)
                                  .Where(y => y.LegacyMappings.Any(z => z.LegacySystemName == "Mainframe - Suffix" &&
                                                                   z.LegacyIdentifier == LegacyIdentifier));

                        ils.ToList().ForEach(profile =>
                        {
                            if (profile.LegacyMappings.Where(mapping => mapping.LegacySystemName == "Mainframe - Suffix").ToList().Count > 1)
                            {
                                results.Add(new ValidationResult("Suffix " + LegacyIdentifier + " shares an ILS Profile with another suffix and cannot be deleted or deactivated."));
                            }
                        });

                        var cci = customer.CCICodingProfiles.Where(x => !x.IsDefault)
                                  .Where(y => y.LegacyMappings.Any(z => z.LegacySystemName == "Mainframe - Suffix" &&
                                                                   z.LegacyIdentifier == LegacyIdentifier));

                        cci.ToList().ForEach(profile =>
                        {
                            if (profile.LegacyMappings.Where(mapping => mapping.LegacySystemName == "Mainframe - Suffix").ToList().Count > 1)
                            {
                                results.Add(new ValidationResult("Suffix " + LegacyIdentifier + " shares a CCI Coding Profile with another suffix and cannot be deleted or deactivated."));
                            }
                        });

                        var reporting = customer.ReportingProfiles.Where(x => !x.IsDefault)
                                        .Where(y => y.LegacyMappings.Any(z => z.LegacySystemName == "Mainframe - Suffix" &&
                                                                         z.LegacyIdentifier == LegacyIdentifier));

                        reporting.ToList().ForEach(profile =>
                        {
                            if (profile.LegacyMappings.Where(mapping => mapping.LegacySystemName == "Mainframe - Suffix").ToList().Count > 1)
                            {
                                results.Add(new ValidationResult("Suffix " + LegacyIdentifier + " shares a Reporting Profile with another suffix and cannot be deleted or deactivated."));
                            }
                        });

                        var credits = customer.CreditsAndAdjustmentsProfiles.Where(x => !x.IsDefault)
                                      .Where(y => y.LegacyMappings.Any(z => z.LegacySystemName == "Mainframe - Suffix" &&
                                                                       z.LegacyIdentifier == LegacyIdentifier));

                        credits.ToList().ForEach(profile =>
                        {
                            if (profile.LegacyMappings.Where(mapping => mapping.LegacySystemName == "Mainframe - Suffix").ToList().Count > 1)
                            {
                                results.Add(new ValidationResult("Suffix " + LegacyIdentifier + " shares a Credits and Adjustments Profile with another suffix and cannot be deleted or deactivated."));
                            }
                        });
                    }
                }
            }
            return(results);
        }
示例#30
0
 public ValidationService(IValidationRepository validationRepository)
 {
     _validationRepository = validationRepository;
 }
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            IRepository           repository           = null;
            IValidationRepository validationRepository = null;
            IFeatureConfiguration featureConfig        = null;

            if (ServiceLocator.IsLocationProviderSet)
            {
                try
                {
                    repository           = ServiceLocator.Current.GetInstance(typeof(IRepository)) as IRepository;
                    validationRepository = ServiceLocator.Current.GetInstance(typeof(IValidationRepository)) as IValidationRepository;
                    featureConfig        = ServiceLocator.Current.GetInstance(typeof(IFeatureConfiguration)) as IFeatureConfiguration;
                }
                catch (ActivationException)
                {
                    //do nothing
                }
            }


            IEnumerable <OrderProfile> orderProfiles = null;

            if (repository != null)
            {
                var suffixLegacyMappingIds = LegacyMappings.Where(lm => lm.LegacySystemName == LegacySystemNames.Suffix.Name).Select(x => x.Id);

                orderProfiles = repository.GetCustomer(CustomerId, RelatedEntitiesEnum.OrderProfiles)
                                .OrderProfiles
                                .Where(scp => scp.LegacyMappings.Any(pplm => suffixLegacyMappingIds.Contains(pplm.Id)));
            }

            #region ClaimCheckerInformation
            if (!string.IsNullOrEmpty(ClaimCheckerInformation))
            {
                if (orderProfiles != null)
                {
                    if (orderProfiles.Any(x => string.IsNullOrEmpty(x.ClaimCheckerReport?.Trim())))
                    {
                        results.Add(new ValidationResult("Cannot use Claim Checker Information if Claim Checker Report is not selected", new[] { "ClaimCheckerInformation" }));
                    }
                }
            }
            #endregion

            #region ClaimCheckerSpecialHandling
            if (!string.IsNullOrEmpty(ClaimCheckerSpecialHandling))
            {
                if (orderProfiles != null)
                {
                    if (orderProfiles.Any(x => string.IsNullOrEmpty(x.ClaimCheckerReport?.Trim())))
                    {
                        results.Add(new ValidationResult("Cannot use Claim Checker Special Handling if Claim Checker Report is not selected", new[] { "ClaimCheckerSpecialHandling" }));
                    }
                }
            }
            #endregion

            #region AlertCustomerIfPriceIncreasesByPercent
            if ((AlertCustomerIfPriceIncreasesByPercent > 0m) && (string.IsNullOrEmpty(PriceIncreaseAlert)))
            {
                results.Add(new ValidationResult("Price Increase Alert month not selected", new[] { "AlertCustomerIfPriceIncreasesByPercent" }));
            }
            if ((AlertCustomerIfPriceIncreasesByPercent == 0m || !AlertCustomerIfPriceIncreasesByPercent.HasValue) && (!string.IsNullOrEmpty(PriceIncreaseAlert)))
            {
                results.Add(new ValidationResult("Price Increase Alert percentage is not provided", new[] { "AlertCustomerIfPriceIncreasesByPercent" }));
            }
            #endregion

            #region EmailAddressesToSendAlert
            if (string.IsNullOrEmpty(EmailAddressesToSendAlert) && !string.IsNullOrEmpty(PriceIncreaseAlert))
            {
                results.Add(new ValidationResult("Price Increase Alert email not provided", new[] { "EmailAddressesToSendAlert" }));
            }
            if (!string.IsNullOrEmpty(EmailAddressesToSendAlert) && string.IsNullOrEmpty(PriceIncreaseAlert))
            {
                results.Add(new ValidationResult("Price Increase Alert month not selected", new[] { "EmailAddressesToSendAlert" }));
            }
            #endregion

            #region PrintJetsCumulativeReport
            if (featureConfig != null)
            {
                if (featureConfig.IsAvailable(FeaturesEnum.AddRemainingCCILines))
                {
                    if ((PrintJetsCumulativeReport == false) && !string.IsNullOrWhiteSpace(JetsCumulativeReportFrequency))
                    {
                        results.Add(new ValidationResult("Cannot add Jets Cumulative Report Frequency.", new[] { "JetsCumulativeReportFrequency" }));
                    }
                    if ((PrintJetsCumulativeReport == false) && !string.IsNullOrWhiteSpace(PrintJetsCumulativeReportComments))
                    {
                        results.Add(new ValidationResult("Cannot add Print Jets Cumulative Report Comments.", new[] { "PrintJetsCumulativeReportComments" }));
                    }
                }
            }
            #endregion


            if (validationRepository != null)
            {
                string errorMessage;
                if (!validationRepository.ValidateProfile(this, out errorMessage))
                {
                    results.Add(new ValidationResult(string.Format("Profile failed SAP validation: {0}", errorMessage), null));
                }
            }

            return(results);
        }
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            var legacyOfficeCodes = LegacyMappings.Select(x => x.LegacyIdentifier.Substring(0, 2)).ToList();

            #region AccountToBeMerged
            if (!string.IsNullOrWhiteSpace(AccountToBeMerged) && IncludeEDIInvoicingDetails == false)
            {
                results.Add(new ValidationResult("Account to be merged is not valid.", new[] { "AccountToBeMerged" }));
            }
            #endregion

            #region CombineSuffixes
            if (CombineSuffixes.HasValue && ConsolidateInvoicing == false)
            {
                results.Add(new ValidationResult("Combine Suffixes cannot be used if account is not consolidated.", new[] { "CombineSuffixes" }));
            }
            #endregion

            #region CommentLineRequiredComments
            if (!string.IsNullOrWhiteSpace(CommentLineRequiredComments) && CommentLineRequired == null)
            {
                results.Add(new ValidationResult("Cannot add Comment Line Required Comments.", new[] { "CommentLineRequiredComments" }));
            }
            #endregion

            #region ConsolidatedInvoiceMonth
            if (ConsolidatedInvoiceMonth == null && ConsolidateInvoicing == true && new[] { "ZE", "ZF", "ZI", "ZN", "ZP", "ZQ", "ZS", "ZT", "ZU", "ZV", "ZY", "ZZ" }.Any(o1 => legacyOfficeCodes.Any(o2 => o1 == o2)))
            {
                results.Add(new ValidationResult("Consolidated Invoice Month must be selected.", new[] { "ConsolidatedInvoiceMonth" }));
            }

            if (ConsolidatedInvoiceMonth != null && ConsolidateInvoicing == false)
            {
                results.Add(new ValidationResult("Consolidated Invoice Month cannot be used if account is not consolidated.", new[] { "ConsolidatedInvoiceMonth" }));
            }
            #endregion

            #region ConsolidatedInvoiceParameters
            if (ConsolidatedInvoiceParameters.HasValue && ConsolidateInvoicing == false)
            {
                results.Add(new ValidationResult("Consolidated Invoice Parameters cannot be used if account is not consolidated.", new[] { "CombineSuffixes" }));
            }
            #endregion

            #region ConsolidatedInvoicing
            IRepository           repository     = null;
            IValidationRepository validationRepo = null;
            IFeatureConfiguration featureConfig  = null;

            try
            {
                string errorMessageConsolidated;
                if (ServiceLocator.IsLocationProviderSet)
                {
                    try
                    {
                        repository     = ServiceLocator.Current.GetInstance(typeof(IRepository)) as IRepository;
                        validationRepo = ServiceLocator.Current.GetInstance(typeof(IValidationRepository)) as IValidationRepository;
                        featureConfig  = ServiceLocator.Current.GetInstance(typeof(IFeatureConfiguration)) as IFeatureConfiguration;
                    }
                    catch (ActivationException)
                    {
                        //do nothing
                    }
                }

                if (!legacyOfficeCodes.All(x => new[] { "BR", "BT", "CG", "DC", "DV", "LA", "RB", "SF", "TN", "TO", "TQ" }.Contains(x)))
                {
                    if (repository != null)
                    {
                        var suffixIds = LegacyMappings.Where(x => x.LegacySystemName == LegacySystemNames.Suffix.Name).Select(x => x.Id).ToArray();

                        var customer          = repository.GetCustomer(CustomerId, RelatedEntitiesEnum.SecondaryCustomerProfiles);
                        var secondaryProfiles = customer.SecondaryCustomerProfiles;
                        var matchingProfiles  = secondaryProfiles.Where(sp => sp.LegacyMappings
                                                                        .Any(splm =>
                                                                             suffixIds.Contains(splm.Id)));

                        if (matchingProfiles.Any())
                        {
                            //var isoCurrency = matchingProfiles.First().ISOBillingCurrency;
                            //var billingCurrency = matchingProfiles.First().EBSCOBillingCurrency;

                            string errorMessage;

                            if (!validationRepo.ValidateConsolidatedInvoices(this, matchingProfiles.First(), out errorMessageConsolidated))
                            {
                                results.Add(new ValidationResult(string.Format(errorMessageConsolidated), null));
                            }
                        }
                    }
                }

                #endregion

                #region DiscountDays
                if ((DiscountDays ?? 0) > 0 && (CashDiscountPercent ?? 0) == 0)
                {
                    results.Add(new ValidationResult("Discount Days is not valid.", new[] { "DiscountDays" }));
                }
                if ((DiscountDays ?? 0) == 0 && (CashDiscountPercent ?? 0) > 0)
                {
                    results.Add(new ValidationResult("Discount Days is not valid.", new[] { "DiscountDays" }));
                }
                #endregion

                #region EDIFileTransmissionMethod
                if (string.IsNullOrWhiteSpace(EDIFileTransmissionMethod) && IncludeEDIInvoicingDetails)
                {
                    results.Add(new ValidationResult("EDI File Transmission Method is required.", new[] { "EDIFileTransmissionMethod" }));
                }
                if (!string.IsNullOrWhiteSpace(EDIFileTransmissionMethod) && IncludeEDIInvoicingDetails == false)
                {
                    results.Add(new ValidationResult("EDI File Transmission Method is not valid.", new[] { "EDIFileTransmissionMethod" }));
                }
                #endregion

                #region EDIForMainRenewalInvoiceOnly
                if (EDIForMainRenewalInvoiceOnly && IncludeEDIInvoicingDetails == false)
                {
                    results.Add(new ValidationResult("EDI For Main Renewal Invoice Only is not valid.", new[] { "EDIForMainRenewalInvoiceOnly" }));
                }
                #endregion

                #region EmailAddressesforAcknowledgements
                if (!string.IsNullOrWhiteSpace(EmailAddressesforAcknowledgements) && IncludeEDIInvoicingDetails == false)
                {
                    results.Add(new ValidationResult("Email Addresses for Acknowledgements is not valid.", new[] { "EmailAddressesforAcknowledgements" }));
                }
                if (string.IsNullOrWhiteSpace(EmailAddressesforAcknowledgements) && ILSFormat != null && new[] { "EBSCO Standard", "Innovative" }.Contains(ILSFormat, StringComparer.OrdinalIgnoreCase))
                {
                    results.Add(new ValidationResult("Email Addresses for Acknowledgements is required.", new[] { "EmailAddressesforAcknowledgements" }));
                }
                #endregion

                #region F24216 - Add EDI System
                if (featureConfig != null)
                {
                    if (featureConfig.IsAvailable(FeaturesEnum.EDISystem))
                    {
                        if (!string.IsNullOrWhiteSpace(EDISystem) && IncludeEDIInvoicingDetails == false)
                        {
                            results.Add(new ValidationResult("EDI System is not valid.", new[] { "EDISystem" }));
                        }
                        if (string.IsNullOrWhiteSpace(EDISystem) && IncludeEDIInvoicingDetails == true)
                        {
                            results.Add(new ValidationResult("EDI System is required.", new[] { "EDISystem" }));
                        }
                    }
                }
                #endregion

                #region F20178 - Add Fund Code (Client Billing info fields)
                if (featureConfig != null)
                {
                    if (featureConfig.IsAvailable(FeaturesEnum.FundCodeFields))
                    {
                        if (FundCodeRequired == 1 && !string.IsNullOrWhiteSpace(FundCodeRequiredComments))
                        {
                            results.Add(new ValidationResult("Cannot add Fund Code Required Comments.", new[] { "FundCodeRequiredComments" }));
                        }
                        if (FundCodeRequired == 1 && !string.IsNullOrWhiteSpace(FundCodeToPrintOnInvoice))
                        {
                            results.Add(new ValidationResult("Cannot add Fund Code to print on Invoice.", new[] { "FundCodeToPrintOnInvoice" }));
                        }
                        if (FundCodeRequired == 2 && FundCodeToPrintOnInvoice?.Length > 6)
                        {
                            results.Add(new ValidationResult("Fund Code to print on Invoice can not be more than 6 characters.", new[] { "FundCodeToPrintOnInvoice" }));
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(HegisNumberRequiredComments) && HegisNumbersRequired == false)
                        {
                            results.Add(new ValidationResult("Cannot add Hegis Number Required Comments.", new[] { "HegisNumberRequiredComments" }));
                        }
                        if (!string.IsNullOrWhiteSpace(HegisNumberRequiredComments) && HegisNumberRequiredComments.StartsWith("------"))
                        {
                            results.Add(new ValidationResult("Hegis Number Required Comments is invalid.", new[] { "HegisNumberRequiredComments" }));
                        }
                        if (!string.IsNullOrWhiteSpace(HegisNumberRequiredComments) &&
                            (HegisNumberRequiredComments.StartsWith("**C") || HegisNumberRequiredComments.StartsWith("**c")) &&
                            !Regex.IsMatch(HegisNumberRequiredComments, @"\*\*[Cc][123]"))
                        {
                            results.Add(new ValidationResult("Hegis Number Required Comments is invalid.", new[] { "HegisNumberRequiredComments" }));
                        }
                    }
                }
                #endregion

                #region ILSFormat
                if (string.IsNullOrWhiteSpace(ILSFormat) && IncludeEDIInvoicingDetails == true)
                {
                    results.Add(new ValidationResult("ILS Format is required.", new[] { "ILSFormat" }));
                }
                if (!string.IsNullOrWhiteSpace(ILSFormat) && IncludeEDIInvoicingDetails == false)
                {
                    results.Add(new ValidationResult("ILS Format is not valid.", new[] { "ILSFormat" }));
                }
                #endregion

                #region InvoiceTypestoInclude
                if (InvoiceTypestoInclude != null && IncludeEDIInvoicingDetails == false)
                {
                    results.Add(new ValidationResult("Invoice Types to Include is not valid.", new[] { "InvoiceTypestoInclude" }));
                }
                #endregion

                #region MaximumInvoiceAmount
                if ((MaximumInvoiceAmount ?? 0) > 0 && (MaximumInvoiceLineItems ?? 0) > 0)
                {
                    results.Add(new ValidationResult("Maximum Invoice Amount and Maximum Line Items are mutually exclusive.", new[] { "MaximumInvoiceAmount" }));
                }
                #endregion

                #region MaximumInvoiceAmountComments
                if (!string.IsNullOrWhiteSpace(MaximumInvoiceAmountComments) && (MaximumInvoiceAmount ?? 0) == 0)
                {
                    results.Add(new ValidationResult("Cannot add Maximum Invoice Amount Comments.", new[] { "MaximumInvoiceAmountComments" }));
                }
                #endregion

                #region MaximumInvoiceLineItems
                if ((MaximumInvoiceAmount ?? 0) > 0 && (MaximumInvoiceLineItems ?? 0) > 0)
                {
                    results.Add(new ValidationResult("Maximum Invoice Amount and Maximum Line Items are mutually exclusive.", new[] { "MaximumInvoiceLineItems" }));
                }
                #endregion

                #region MaximumInvoiceLineItemsComments
                if (!string.IsNullOrWhiteSpace(MaximumInvoiceLineItemsComments) && (MaximumInvoiceLineItems ?? 0) == 0)
                {
                    results.Add(new ValidationResult("Cannot add Maximum Invoice Line Items Comments.", new[] { "MaximumInvoiceLineItemsComments" }));
                }
                #endregion

                #region PeriodSplit
                if (PeriodSplit != null && !legacyOfficeCodes.All(x => new[] { "ZE", "ZF", "ZI", "ZN", "ZP", "ZQ", "ZS", "ZT", "ZU", "ZV", "ZY", "ZZ" }.Contains(x)))
                {
                    results.Add(new ValidationResult("Period Split cannot be selected for this office code.", new[] { "PeriodSplit" }));
                }
                if (PeriodSplit != null && ConsolidateInvoicing == false)
                {
                    results.Add(new ValidationResult("Period Split cannot be used if account is not consolidated.", new[] { "PeriodSplit" }));
                }
                #endregion

                #region ProcessImmediately
                if (ProcessImmediately && ConsolidateInvoicing == false)
                {
                    results.Add(new ValidationResult("Process Immediately cannot be used if account is not consolidated.", new[] { "ProcessImmediately" }));
                }
                #endregion

                #region HoldUntilCurrentRatesAvailable
                if (HoldUntilCurrentRatesAvailable && ConsolidateInvoicing == false)
                {
                    results.Add(new ValidationResult("Hold Until Current Rates Available cannot be used if account is not consolidated.", new[] { "ProcessImmediately" }));
                }
                #endregion

                #region SortbyISC
                if (!string.IsNullOrWhiteSpace(SortbyISC) && SortbyISC != "S" && TSCRequired == true)
                {
                    results.Add(new ValidationResult("Sort by ISC is not valid.", new[] { "SortbyISC" }));
                }
                #endregion

                #region SpecialInstructions
                if (!string.IsNullOrWhiteSpace(SpecialInstructions) && IncludeEDIInvoicingDetails == false)
                {
                    results.Add(new ValidationResult("Special Instructions is not valid.", new[] { "MaximumInvoiceLineItemsComments" }));
                }
                #endregion

                #region TSCRequiredComments
                if (!string.IsNullOrWhiteSpace(TSCRequiredComments) && TSCRequired == false)
                {
                    results.Add(new ValidationResult("Cannot add TSC Required Comments.", new[] { "TSCRequiredComments" }));
                }
                #endregion

                #region UseC1CommentComments
                if (!string.IsNullOrWhiteSpace(UseC1CommentComments) && UseC1Comment == false)
                {
                    results.Add(new ValidationResult("Cannot add Use C1* Comment Comments.", new[] { "UseC1CommentComments" }));
                }
                #endregion

                #region UseC3CommentComments
                if (!string.IsNullOrWhiteSpace(UseC3CommentComments) && UseC3Comment == false)
                {
                    results.Add(new ValidationResult("Cannot add Use C3* Comment Comments.", new[] { "UseC3CommentComments" }));
                }
                #endregion

                #region BreakAdjustmentsBySubscriber
                if (BreakAdjustmentsbySubscriber && OriginalInvoiceItemCount > 0)
                {
                    results.Add(new ValidationResult("Break Adjustments by Subscriber is invalid.", new[] { "BreakAdjustmentsbySubscriber" }));
                }
                if (BreakAdjustmentsbySubscriber && SupplementalInvoiceItemCount > 0)
                {
                    results.Add(new ValidationResult("Break Adjustments by Subscriber is invalid.", new[] { "BreakAdjustmentsbySubscriber" }));
                }
                #endregion

                #region F13205;
                if (featureConfig != null)
                {
                    IEnumerable <BillingLocation> billingLocations = null;
                    var CcisAddedToInvoicesProfileFeatureEnabled   = featureConfig.IsAvailable(FeaturesEnum.CcisAddedToInvoicesProfile);

                    if (CcisAddedToInvoicesProfileFeatureEnabled)
                    {
                        if (IncludeInvoiceDetailReport == true && PrintInvoicesInOldFormat == true)
                        {
                            results.Add(new ValidationResult("Cannot include Invoice Detail Report if Invoice is printed in old format.", new[] { "IncludeInvoiceDetailReport" }));
                        }

                        if (PrintPageTotal == true && PrintRunningSubTotal == true)
                        {
                            results.Add(new ValidationResult("Cannot print both Running Sub-Total and Page Total on an Invoice.", new[] { "PrintPageTotal" }));
                        }

                        // if (featureConfig.IsAvailable(FeaturesEnum.ManageBillingAddresses))
                        if (featureConfig.IsAvailable("CA.F7222.US326097.BillingLocationSAPSync"))
                        {
                            if (repository != null && !IsDefault)
                            {
                                var suffixLegacyMappingIds = LegacyMappings.Where(lm => lm.LegacySystemName == LegacySystemNames.Suffix.Name).Select(x => x.Id);

                                billingLocations = repository.GetCustomer(CustomerId, RelatedEntitiesEnum.BillingLocations)
                                                   .BillingLocations.Where(x => x.LegacyMappings.Any(lm => suffixLegacyMappingIds.Contains(lm.Id)))
                                                   .ToArray();

                                if (SplitPaymentUsePublicAdministrationVATMatrix && !billingLocations.All(x => x.CountryCode.Equals("IT")))
                                {
                                    results.Add(new ValidationResult("Public Administration VAT Matrix is only available in Italy.", new[] { "SplitPaymentUsePublicAdministrationVatMatrix" }));
                                }
                            }
                        }
                        else
                        {
                            if (SplitPaymentUsePublicAdministrationVATMatrix == true && !legacyOfficeCodes.Any(x => new[] { "ZI", "ZQ" }.Contains(x)))
                            {
                                results.Add(new ValidationResult("Public Administration VAT Matrix is only available in Italy.", new[] { "SplitPaymentUsePublicAdministrationVatMatrix" }));
                            }
                        }


                        //begin - can move to attributes when feature CA.F13205 enabled
                        if (string.IsNullOrWhiteSpace(MailInvoicesTo))
                        {
                            results.Add(new ValidationResult("Mail Invoices To is a required field.", new[] { "MailInvoicesTo" }));
                        }

                        Regex regex = new Regex(@"(([a-zA-Z0-9_\-\.']+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,63}|[0-9]{1,3})(\]?)(\s*;\s*|\s*$))*");
                        if (!string.IsNullOrEmpty(AlternateReplyToEmailAddressForInvoices))
                        {
                            if (AlternateReplyToEmailAddressForInvoices.Length > 100)
                            {
                                results.Add(new ValidationResult("Alternate Reply To Email Address for Invoices exceeds maximum length of 100.", new[] { "AlternateReplyToEmailAddressForInvoices" }));
                            }

                            var email = regex.Match(AlternateReplyToEmailAddressForInvoices);
                            if (email.Value.Length != AlternateReplyToEmailAddressForInvoices.Length)
                            {
                                results.Add(new ValidationResult("Alternate Reply to Email Addresses for Invoices is invalid.  Multiple emails should be seperated by a semicolon ';'", new[] { "AlternateReplyToEmailAddressForInvoices" }));
                            }
                        }

                        if (!string.IsNullOrEmpty(EmailAddressForOvernightEdits))
                        {
                            if (EmailAddressForOvernightEdits.Length > 200)
                            {
                                results.Add(new ValidationResult("Email Address for Overnight Edits exceeds maximum length of 200.", new[] { "EmailAddressForOvernightEdits" }));
                            }
                            var email = regex.Match(EmailAddressForOvernightEdits);
                            if (email.Value.Length != EmailAddressForOvernightEdits.Length)
                            {
                                results.Add(new ValidationResult("Email Addresses for Overnight Edits is invalid..  Multiple emails should be seperated by a semicolon ';'", new[] { "EmailAddressForOvernightEdits" }));
                            }
                        }
                        //end - can move to attributes when feature CA.F13205 enabled
                    }
                }
                #endregion

                if (validationRepo != null)
                {
                    string errorMessage;
                    if (!validationRepo.ValidateProfile(this, out errorMessage))
                    {
                        results.Add(new ValidationResult(string.Format("Profile failed SAP validation: {0}", errorMessage), null));
                    }
                }

                return(results);
            }
            finally
            {
                repository?.Dispose();
                validationRepo?.Dispose();
            }
        }
        public static ValidationResult Validate <TSource>(this IValidationRepository repository, TSource source, Action <ValidationRuleFactory <TSource> > init)
        {
            var factory = repository.Create(source, init);

            return(factory.ValidateObject(source, new ValidationContext()));
        }
        public new IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            IFeatureConfiguration featureConfig = null;

            if (ServiceLocator.IsLocationProviderSet)
            {
                try
                {
                    featureConfig = ServiceLocator.Current.GetInstance(typeof(IFeatureConfiguration)) as IFeatureConfiguration;
                }
                catch (ActivationException)
                {
                    //do nothing
                }
            }

            var results = new List <ValidationResult>();

            if ((new[] { "US", "CA" }.Contains(CountryCode)) && string.IsNullOrWhiteSpace(PostalCode))
            {
                results.Add(new ValidationResult("Postal is required.", new[] { "Postal" }));
            }

            if (CountryCode == "US" && PostalCode != null && !Regex.Match(PostalCode, @"^\d{1,5}(\-\d{4})?$").Success)
            {
                results.Add(new ValidationResult("Postal is not valid.", new[] { "Postal" }));
            }

            if ((new[] { "US", "CA", "AU" }.Contains(CountryCode)) && string.IsNullOrWhiteSpace(StateProvince))
            {
                results.Add(new ValidationResult("State is required.", new[] { "StateProvince" }));
            }

            if (CountryCode == "CA" && PostalCode != null && !Regex.Match(PostalCode, @"(\D\d\D\s\d\D\d)").Success)
            {
                results.Add(new ValidationResult("Postal is not valid.", new[] { "Postal" }));
            }

            if (FteCounts?.Select(x => x.CountType).Distinct().Count() != FteCounts?.Select((x => x.CountType)).Count())
            {
                results.Add(new ValidationResult("FTE Type cannot be selected more than once.", new[] { "Fte" }));
            }

            if (ShippingProfile != null)
            {
                var tempGST = ShippingProfile.GSTExempt.HasValue ? (bool)ShippingProfile.GSTExempt : false;
                var tempQST = ShippingProfile.QSTExempt.HasValue ? (bool)ShippingProfile.QSTExempt : false;

                if (CountryCode != "CA" && tempGST)
                {
                    results.Add(new ValidationResult("Country cannot be GST Exempt.", new[] { "GST Exempt" }));
                }

                if (CountryCode != "CA" && tempQST)
                {
                    results.Add(new ValidationResult("Country cannot be QST Exempt.", new[] { "QST Exempt" }));
                }

                //LANGUAGE
                var accountLegacyMapping = LegacyMappings.FirstOrDefault(x => x.LegacySystemName == LegacySystemNames.Account.Name);
                if (accountLegacyMapping != null)
                {
                    if (!string.IsNullOrWhiteSpace(ShippingProfile.Language) &&
                        !accountLegacyMapping.LegacyIdentifier.StartsWith("Z") &&
                        !new[] { "AU", "BA", "FB", "JA", "KO", "NZ", "TO", "TQ", "TW" }.Contains(accountLegacyMapping.LegacyIdentifier.Substring(0, 2)))
                    {
                        results.Add(new ValidationResult("Language cannot be selected for this office.", new[] { "Language" }));
                    }

                    if (!string.IsNullOrWhiteSpace(ShippingProfile.Language) &&
                        //!new[] { "DU - Dutch", "EN - Englisth", "FR - French", "GE - German", "IT - Italian", "PR - Portuguese", "SO - South African", "SP - Spanish", "TU - Turkish" }.Contains(ShippingProfile.Language))
                        !new[] { "DU", "EN", "FR", "GE", "IT", "PR", "SO", "SP", "TU" }.Contains(ShippingProfile.Language))
                    {
                        results.Add(new ValidationResult("Language code is invalid.", new[] { "Language" }));
                    }

                    if (featureConfig.IsAvailable(FeaturesEnum.SplitTaxExemptAndVatOnShippingProfile))
                    {
                        if (ShippingProfile != null)
                        {
                            if (accountLegacyMapping.LegacyIdentifier.StartsWith("Z") && !string.IsNullOrEmpty(ShippingProfile.TaxExemptNumber))
                            {
                                results.Add(new ValidationResult("Tax Exempt Number cannot be used for this office."));
                            }

                            //VAT Number  Office != Z * Value is not null   VAT Number cannot be used for this office.
                            if (!string.IsNullOrEmpty(ShippingProfile.VATNumber) && !accountLegacyMapping.LegacyIdentifier.StartsWith("Z"))
                            {
                                results.Add(new ValidationResult("VAT Number cannot be used for this office.", new[] { "VATNumber" }));
                            }
                        }
                    }
                }

                //ITEM FORMATS
                var ItemFormat1Thru6 = new List <string>();

                if (!string.IsNullOrWhiteSpace(ShippingProfile.ItemFormat1))
                {
                    ItemFormat1Thru6.Add(ShippingProfile.ItemFormat1);
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.ItemFormat2))
                {
                    ItemFormat1Thru6.Add(ShippingProfile.ItemFormat2);
                    if (ItemFormat1Thru6.Distinct().Count() != ItemFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Item Formats cannot be selected more than once.", new[] { "ItemFormat2" }));
                    }
                }


                if (!string.IsNullOrWhiteSpace(ShippingProfile.ItemFormat3))
                {
                    ItemFormat1Thru6.Add(ShippingProfile.ItemFormat3);
                    if (ItemFormat1Thru6.Distinct().Count() != ItemFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Item Formats cannot be selected more than once.", new[] { "ItemFormat3" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.ItemFormat4))
                {
                    ItemFormat1Thru6.Add(ShippingProfile.ItemFormat4);
                    if (ItemFormat1Thru6.Distinct().Count() != ItemFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Item Formats cannot be selected more than once.", new[] { "ItemFormat4" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.ItemFormat5))
                {
                    ItemFormat1Thru6.Add(ShippingProfile.ItemFormat5);
                    if (ItemFormat1Thru6.Distinct().Count() != ItemFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Item Formats cannot be selected more than once.", new[] { "ItemFormat5" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.ItemFormat6))
                {
                    ItemFormat1Thru6.Add(ShippingProfile.ItemFormat6);
                    if (ItemFormat1Thru6.Distinct().Count() != ItemFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Item Formats cannot be selected more than once.", new[] { "ItemFormat6" }));
                    }
                }

                //STANDARD FORMATS
                var StandardFormat1Thru6 = new List <string>();

                if (!string.IsNullOrWhiteSpace(ShippingProfile.StandardFormat1))
                {
                    StandardFormat1Thru6.Add(ShippingProfile.StandardFormat1);
                    if (ItemFormat1Thru6.Contains(ShippingProfile.StandardFormat1))
                    {
                        results.Add(new ValidationResult("Format cannot be selected as both Standard and Item Format.", new[] { "StandardFormat1" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.StandardFormat2))
                {
                    StandardFormat1Thru6.Add(ShippingProfile.StandardFormat2);
                    if (StandardFormat1Thru6.Distinct().Count() != StandardFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Standard Formats cannot be selected more than once.", new[] { "StandardFormat2" }));
                    }
                    if (ItemFormat1Thru6.Contains(ShippingProfile.StandardFormat2))
                    {
                        results.Add(new ValidationResult("Format cannot be selected as both Standard and Item Format.", new[] { "StandardFormat2" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.StandardFormat3))
                {
                    StandardFormat1Thru6.Add(ShippingProfile.StandardFormat3);
                    if (StandardFormat1Thru6.Distinct().Count() != StandardFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Standard Formats cannot be selected more than once.", new[] { "StandardFormat3" }));
                    }
                    if (ItemFormat1Thru6.Contains(ShippingProfile.StandardFormat3))
                    {
                        results.Add(new ValidationResult("Format cannot be selected as both Standard and Item Format.", new[] { "StandardFormat3" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.StandardFormat4))
                {
                    StandardFormat1Thru6.Add(ShippingProfile.StandardFormat4);
                    if (StandardFormat1Thru6.Distinct().Count() != StandardFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Standard Formats cannot be selected more than once.", new[] { "StandardFormat4" }));
                    }
                    if (ItemFormat1Thru6.Contains(ShippingProfile.StandardFormat4))
                    {
                        results.Add(new ValidationResult("Format cannot be selected as both Standard and Item Format.", new[] { "StandardFormat4" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.StandardFormat5))
                {
                    StandardFormat1Thru6.Add(ShippingProfile.StandardFormat5);
                    if (StandardFormat1Thru6.Distinct().Count() != StandardFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Standard Formats cannot be selected more than once.", new[] { "StandardFormat5" }));
                    }
                    if (ItemFormat1Thru6.Contains(ShippingProfile.StandardFormat5))
                    {
                        results.Add(new ValidationResult("Format cannot be selected as both Standard and Item Format.", new[] { "StandardFormat5" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.StandardFormat6))
                {
                    StandardFormat1Thru6.Add(ShippingProfile.StandardFormat6);
                    if (StandardFormat1Thru6.Distinct().Count() != StandardFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Standard Formats cannot be selected more than once.", new[] { "StandardFormat6" }));
                    }
                    if (ItemFormat1Thru6.Contains(ShippingProfile.StandardFormat6))
                    {
                        results.Add(new ValidationResult("Format cannot be selected as both Standard and Item Format.", new[] { "StandardFormat6" }));
                    }
                }

                //RATE CLASS
                if (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Institution) &&
                    ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Individual))
                {
                    results.Add(new ValidationResult("Individual and Institution are mutually exclusive.", new[] { "RateClass" }));
                }

                if (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularEducator) &&
                    ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialEducator))
                {
                    results.Add(new ValidationResult("Special Educator and Regular Educator are mutually exclusive.", new[] { "RateClass" }));
                }

                if (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularProfessional) &&
                    ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialProfessional))
                {
                    results.Add(new ValidationResult("Special Professional and Regular Professional are mutually exclusive.", new[] { "RateClass" }));
                }

                if ((ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularEducator) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialEducator)) &&
                    (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularProfessional) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialProfessional) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Field) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Military)))
                {
                    results.Add(new ValidationResult("Rate Class selection is mutually exclusive.", new[] { "RateClass" }));
                }

                if ((ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularProfessional) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialProfessional)) &&
                    (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialEducator) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularEducator) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Field) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Military)))
                {
                    results.Add(new ValidationResult("Rate Class selection is mutually exclusive.", new[] { "RateClass" }));
                }

                if (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Field) &&
                    (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialEducator) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularEducator) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Military) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialProfessional) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularProfessional)))
                {
                    results.Add(new ValidationResult("Rate Class selection is mutually exclusive.", new[] { "RateClass" }));
                }

                if (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Military) &&
                    (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialEducator) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularEducator) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Field) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialProfessional) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularProfessional)))
                {
                    results.Add(new ValidationResult("Rate Class selection is mutually exclusive.", new[] { "RateClass" }));
                }


                #region Postage
                if (featureConfig.IsAvailable(FeaturesEnum.AddJetsDropAddress))
                {
                    if (!string.IsNullOrEmpty(ShippingProfile.Postage))
                    {
                        string countryCode = CountryCode;
                        bool   isAlternateShippingAddress = false;

                        if (JetsAddress != null)
                        {
                            countryCode = JetsAddress.CountryCode;
                            isAlternateShippingAddress = true;
                        }
                        else if (DropAddress != null)
                        {
                            countryCode = DropAddress.CountryCode;
                            isAlternateShippingAddress = true;
                        }

                        if (ShippingProfile.Postage == " " && countryCode != "US")
                        {
                            results.Add(isAlternateShippingAddress
                                ? new ValidationResult("US postage may not be valid based on alternate shipping address.",
                                                       new[] { "Postage" })
                                : new ValidationResult("US postage may not be valid based on shipping address.",
                                                       new[] { "Postage" }));
                        }

                        if (ShippingProfile.Postage != " " && countryCode == "US")
                        {
                            results.Add(isAlternateShippingAddress
                                ? new ValidationResult("Postage must be US based on alternate shipping address.",
                                                       new[] { "Postage" })
                                : new ValidationResult("Postage must be US based on shipping address.",
                                                       new[] { "Postage" }));
                        }
                    }
                }
                #endregion
            }

            #region JetsAddress.JetsServiceChargePercent
            if (JetsAddress != null)
            {
                var accountLegacyMapping = LegacyMappings.FirstOrDefault(x => x.LegacySystemName == "Mainframe - Account");
                if (accountLegacyMapping != null)
                {
                    if ((JetsAddress.JetsServiceChargePercent > 0m) &&
                        (!new[] { "AU", "BA", "FB", "JA", "KO", "MX", "TW", "ZE", "ZF", "ZI", "ZJ", "ZN", "ZP", "ZQ", "ZR", "ZS", "ZT", "ZU", "ZV", "ZX", "ZY", "ZZ" }.Contains(accountLegacyMapping.LegacyIdentifier.Substring(0, 2))))
                    {
                        results.Add(new ValidationResult("JETS Service Charge Percent cannot be used for this office.", new[] { "JetsServiceChargePercent" }));
                    }
                }
            }
            #endregion

            if (results.Count > 0)
            {
                return(results);
            }


            IValidationRepository validator  = null;
            IRepository           repository = null;
            try
            {
                if (ServiceLocator.IsLocationProviderSet)
                {
                    try
                    {
                        validator  = ServiceLocator.Current.GetInstance <IValidationRepository>();
                        repository = ServiceLocator.Current.GetInstance(typeof(IRepository)) as IRepository;
                    }
                    catch (ActivationException) { }
                }



                //var context = new ValidationContext(Address, serviceProvider: null, items: null);
                //var result = Validator.TryValidateObject(Address, context, results, true);
                //if(!result)
                //    return results;

                //IRepository repository = null;
                ////IListLookupService lookupService = null;
                //if (ServiceLocator.IsLocationProviderSet)
                //    try
                //    {
                //        //repository = ServiceLocator.Current.GetInstance(typeof(IRepository)) as IRepository;
                //        //lookupService = ServiceLocator.Current.GetInstance(typeof(IListLookupService)) as IListLookupService;
                //    }
                //    catch (ActivationException)
                //    {
                //        //do nothing
                //    }

                /* validate the address using the tax service */
                if (validator != null)
                {
                    if (!validator.ValidateTaxAddress(this))
                    {
                        results.Add(new ValidationResult("Shipping Address is not tax compliant.  City and/or Postal Code are invalid for the selected Country.", new[] { "SystemAddress" }));
                    }
                }

                if (LegacyMappings.Any(x => x.LegacySystemName == LegacySystemNames.Subscriber.Name))
                {
                    if (MainframeAddressOverride == null)
                    {
                        if (LegacyMappings.Any(x => x.LegacySystemName == LegacySystemNames.Subscriber.Name))
                        {
                            if (repository != null)
                            {
                                var formatter        = new MainframeAddressFormatter(repository);
                                var convertedAddress = formatter.ConvertShippingAddress(this);
                                if (
                                    (convertedAddress.Name ?? string.Empty).Length > 30 ||
                                    (convertedAddress.Line1 ?? string.Empty).Length > 30 ||
                                    (convertedAddress.Line2 ?? string.Empty).Length > 30 ||
                                    (convertedAddress.Line3 ?? string.Empty).Length > 30 ||
                                    (convertedAddress.Line4 ?? string.Empty).Length > 30
                                    )
                                {
                                    results.Add(new ValidationResult("Shipping Address is not mainframe compliant. Please use Mainframe Override address."));
                                }
                            }
                        }
                    }
                    else
                    {
                        /* Check if the shipping address is mainframe compliant and still mainframe override address is provided  */
                        if (repository != null)
                        {
                            var formatter        = new MainframeAddressFormatter(repository);
                            var convertedAddress = formatter.ConvertShippingAddress(this);
                            if (
                                (convertedAddress.Name ?? string.Empty).Length <= 30 &&
                                (convertedAddress.Line1 ?? string.Empty).Length <= 30 &&
                                (convertedAddress.Line2 ?? string.Empty).Length <= 30 &&
                                (convertedAddress.Line3 ?? string.Empty).Length <= 30 &&
                                (convertedAddress.Line4 ?? string.Empty).Length <= 30
                                )
                            {
                                results.Add(new ValidationResult(
                                                "Shipping Address is mainframe compliant. Please remove Mainframe Override address."));
                                return(results);
                            }
                        }

                        var context = new ValidationContext(MainframeAddressOverride, serviceProvider: null, items: null);
                        Validator.TryValidateObject(MainframeAddressOverride, context, results, true);
                    }

                    if (TapeAddress != null)
                    {
                        var context = new ValidationContext(TapeAddress, serviceProvider: null, items: null);
                        Validator.TryValidateObject(TapeAddress, context, results, true);
                    }

                    if (JetsAddress != null)
                    {
                        var context = new ValidationContext(JetsAddress, serviceProvider: null, items: null);
                        Validator.TryValidateObject(JetsAddress, context, results, true);
                    }

                    if (DropAddress != null)
                    {
                        var context = new ValidationContext(DropAddress, serviceProvider: null, items: null);
                        Validator.TryValidateObject(DropAddress, context, results, true);
                    }

                    if (ShippingProfile != null)
                    {
                        var context = new ValidationContext(ShippingProfile, serviceProvider: null, items: null);
                        Validator.TryValidateObject(ShippingProfile, context, results, true);
                    }

                    if (LegacyMappings.Count > 0)
                    {
                        if (repository == null)
                        {
                            return(results);
                        }

                        var accountLegacyMapping = LegacyMappings.FirstOrDefault(x => x.LegacySystemName == LegacySystemNames.Account.Name);
                        if (accountLegacyMapping == null)
                        {
                            return(results);
                        }

                        var subcodeLegacyMapping = LegacyMappings.FirstOrDefault(x => x.LegacySystemName == LegacySystemNames.Subscriber.Name);

                        if (subcodeLegacyMapping != null)
                        {
                            if (subcodeLegacyMapping.LegacyIdentifier.Length < 10)
                            {
                                results.Add(new ValidationResult("Subscriber Mapping is not 2 character long.", new[] { "Subscriber Code" }));
                            }

                            var existingCustomer = repository.GetCustomer(CustomerId, RelatedEntitiesEnum.ShippingLocations);
                            foreach (var location in existingCustomer.ShippingLocations.Where(x => x.Id != Id && x.LegacyMappings.Any(alm => alm.Id == accountLegacyMapping.Id)))
                            {
                                if (location.LegacyMappings.Any(x => x.LegacySystemName == LegacySystemNames.Subscriber.Name && x.LegacyIdentifier == subcodeLegacyMapping.LegacyIdentifier))
                                {
                                    results.Add(new ValidationResult("Subscriber is already mapped to an existing address.", new[] { "Subscriber Code" }));
                                    break;
                                }
                            }

                            var countries = repository.GetCountries();
                            var country   = countries.FirstOrDefault(x => x.Value == CountryCode);
                            if (string.IsNullOrEmpty(country?.MainframeShortCode) && MainframeAddressOverride == null)
                            {
                                results.Add(new ValidationResult("Shipping Address is not mainframe compliant. Mainframe does not support the specified country.  Please use Mainframe Override Address."));
                            }
                        }
                    }

                    if (ShippingProfile != null)
                    {
                        if (!string.IsNullOrWhiteSpace(ShippingProfile.VATCountryCode) && !LegacyMappings[0].LegacyIdentifier.StartsWith("Z"))
                        {
                            results.Add(new ValidationResult("VAT Country Code cannot be selected for this office.", new[] { "VATCountryCode" }));
                        }
                    }

                    return(results);
                }
                else
                {
                    if (TapeAddress != null)
                    {
                        results.Add(new ValidationResult("Tape Address cannot be provided without a subscriber code.", new[] { "Tape Address" }));
                    }
                }
                return(results);
            }
            finally
            {
                validator?.Dispose();
                repository?.Dispose();
            }
        }
 public FuelIdValidator(IValidationRepository repository) : base("FuelId is not valid")
 {
     _repository = repository;
 }
 public SettingsAuthenticatonProvider(IValidationRepository repository)
 {
     this.repository = repository;
 }