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);
        }
예제 #2
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            var range = default(V4IPRange);

            try
            {
                range = new V4IPRange(this);
            }
            catch (Exception e)
            {
                results.Add(new ValidationResult(e.Message));
            }

            if (TerminationDate.HasValue)
            {
                if (TerminationDate < DateTime.UtcNow)
                {
                    results.Add(new ValidationResult("Termination date cannot be a date in the past."));
                }
                if (TerminationDate < StartDate)
                {
                    results.Add(new ValidationResult("Termination date cannot come before the start date."));
                }
            }

            // Check to see if IP address range is public
            if (!range.IsIPAddressPublic())
            {
                results.Add(new ValidationResult("IP address or range of address contains non-public IP addresses."));
            }

            if (!IsDeleted)
            {
                if (LegacyMappings != null)
                {
                    if (!(LegacyMappings.Where(x => x.IsActive).ToList().Count > 0))
                    {
                        results.Add(new ValidationResult(
                                        "IP address must be mapped to at least one account, subscriber, or suffix."));
                    }
                }
            }

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

            IRepository repository = null;

            try
            {
                repository = ServiceLocator.IsLocationProviderSet ? ServiceLocator.Current.GetInstance <IRepository>() : null;
            }
            catch (Exception)
            {
                return(results);
            }
            if (repository == null)
            {
                return(results);
            }

            using (repository)
            {
                // Check to make sure edits do not modify ip address values or start date
                if (Id > 0)
                {
                    var oldRecord = repository.GetIPAddress(Id);
                    if (oldRecord == null)
                    {
                        results.Add(
                            new ValidationResult("Unable to find existing IP Address record to validate against"));
                        return(results);
                    }
                    if (IpAddressFromNode1 != oldRecord.IpAddressFromNode1 ||
                        IpAddressFromNode2 != oldRecord.IpAddressFromNode2 ||
                        IpAddressFromNode3 != oldRecord.IpAddressFromNode3 ||
                        IpAddressFromNode4 != oldRecord.IpAddressFromNode4 ||
                        IpAddressToNode1 != oldRecord.IpAddressToNode1 ||
                        IpAddressToNode2 != oldRecord.IpAddressToNode2 ||
                        IpAddressToNode3 != oldRecord.IpAddressToNode3 ||
                        IpAddressToNode4 != oldRecord.IpAddressToNode4 ||
                        StartDate.Date != oldRecord.StartDate.Date)
                    {
                        results.Add(new ValidationResult("IP Address values and start date cannot be updated. "));
                        return(results);
                    }
                }

                // Check for overlaps with existing account, suffix, and subscriber mappings
                var overlaps = repository.GetIPAddressesByCustomerId(CustomerId)
                               .Where(ip => ip.Id != Id &&
                                      new V4IPRange(ip).HasOverlap(range) &&
                                      ip.LegacyMappings.Any(lm => LegacyMappings.Any(nlm => nlm.Id == lm.Id)))
                               .ToList();

                if (overlaps.Count > 0)
                {
                    foreach (var overlap in overlaps)
                    {
                        var mappingStrings = overlap.LegacyMappings
                                             .Where(lm => LegacyMappings.Any(nlm => lm.Id == nlm.Id))
                                             .Select(GetLegacyShortDescription);
                        var mappingListString = string.Concat(mappingStrings).TrimEnd(',');

                        results.Add(new ValidationResult(
                                        $"The IP address range {range} overlaps with exising IP address range {new V4IPRange(overlap)}, and both have the following matching mappings:{mappingListString}."));
                    }
                }
            }

            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();
            }
        }
예제 #4
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);
        }
        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);
        }