public ProducerCharge GetProducerChargeBand(schemeType schmemeType, producerType producerType, MemberUpload memberUpload)
        {
            var complianceYear = int.Parse(schmemeType.complianceYear);

            var previousProducerSubmission =
                registeredProducerDataAccess.GetProducerRegistration(producerType.registrationNo, complianceYear, schmemeType.approvalNo, memberUpload);

            var previousAmendmentCharge =
                registeredProducerDataAccess.HasPreviousAmendmentCharge(producerType.registrationNo, complianceYear, schmemeType.approvalNo, memberUpload);

            var chargeband = environmentAgencyProducerChargeBandCalculator.GetProducerChargeBand(schmemeType, producerType, memberUpload);

            if (previousProducerSubmission != null)
            {
                Log.Information(string.Format("previous {0}", previousProducerSubmission.Id));
                Log.Information(string.Format("previous amendment {0}", previousAmendmentCharge.ToString()));
                if (!previousAmendmentCharge && (producerType.eeePlacedOnMarketBand == eeePlacedOnMarketBandType.Morethanorequalto5TEEEplacedonmarket &&
                                                 previousProducerSubmission.EEEPlacedOnMarketBandType == (int)eeePlacedOnMarketBandType.Lessthan5TEEEplacedonmarket))
                {
                    return(chargeband);
                }
            }

            return(new ProducerCharge()
            {
                ChargeBandAmount = chargeband.ChargeBandAmount,
                Amount = 0
            });
        }
        public IEnumerable <RuleResult> Evaluate(schemeType scheme)
        {
            var duplicateProducerNames = new List <string>();

            foreach (var producer in scheme.producerList)
            {
                if (!string.IsNullOrEmpty(producer.GetProducerName()))
                {
                    var isDuplicate = scheme.producerList
                                      .Any(p => p != producer && p.GetProducerName() == producer.GetProducerName());

                    if (isDuplicate && !duplicateProducerNames.Contains(producer.GetProducerName()))
                    {
                        duplicateProducerNames.Add(producer.GetProducerName());
                        yield return
                            (RuleResult.Fail(
                                 string.Format("{0} can only appear once in your file. Review your file.",
                                               producer.GetProducerName())));

                        continue;
                    }
                }

                yield return(RuleResult.Pass());
            }
        }
        public IEnumerable<RuleResult> Evaluate(schemeType scheme)
        {
            var duplicateRegistrationNumbers = new List<string>();

            foreach (var producer in scheme.producerList)
            {
                if (!string.IsNullOrEmpty(producer.registrationNo))
                {
                    var isDuplicate = scheme.producerList
                        .Any(p => p != producer && p.registrationNo == producer.registrationNo);

                    if (isDuplicate && !duplicateRegistrationNumbers.Contains(producer.registrationNo))
                    {
                        duplicateRegistrationNumbers.Add(producer.registrationNo);
                        yield return
                            RuleResult.Fail(
                                string.Format(
                                    "Producer registration number (PRN) {0} can only appear once in your XML file. Review your file.",
                                    producer.registrationNo));
                        continue;
                    }
                }

                yield return RuleResult.Pass();
            }
        }
        public RuleResult Evaluate(schemeType root, producerType element, Guid organisationId)
        {
            var result = RuleResult.Pass();

            if (element.status == statusType.A)
            {
                var existingProducer =
                    querySet.GetLatestProducerForComplianceYearAndScheme(element.registrationNo, root.complianceYear, organisationId);

                if (existingProducer != null)
                {
                    var existingChargeBandType = existingProducer.ChargeBandAmount.ChargeBand;

                    var producerCharge = Task.Run(() => producerChargeBandCalculatorChooser.GetProducerChargeBand(root, element)).Result;

                    if (existingChargeBandType != producerCharge.ChargeBandAmount.ChargeBand)
                    {
                        result = RuleResult.Fail(
                            string.Format("The charge band of {0} {1} will change from '{2}' to '{3}'.",
                                          existingProducer.OrganisationName,
                                          existingProducer.RegisteredProducer.ProducerRegistrationNumber,
                                          existingChargeBandType,
                                          producerCharge.ChargeBandAmount.ChargeBand),
                            Core.Shared.ErrorLevel.Warning);
                    }
                }
            }

            return(result);
        }
        public RuleResult Evaluate(schemeType root, producerType element, Guid organisationId)
        {
            var result = RuleResult.Pass();

            if (element.status == statusType.A)
            {
                var existingProducer =
                    querySet.GetLatestProducerForComplianceYearAndScheme(element.registrationNo, root.complianceYear, organisationId);

                if (existingProducer != null)
                {
                    ChargeBand existingChargeBandType = existingProducer.ChargeBandAmount.ChargeBand;

                    ChargeBand newChargeBandType = producerChargeBandCalculator.GetProducerChargeBand(
                        element.annualTurnoverBand,
                        element.VATRegistered,
                        element.eeePlacedOnMarketBand);

                    if (existingChargeBandType != newChargeBandType)
                    {
                        result = RuleResult.Fail(
                           string.Format("The charge band of {0} {1} will change from '{2}' to '{3}'.",
                              existingProducer.OrganisationName,
                              existingProducer.RegisteredProducer.ProducerRegistrationNumber,
                              existingChargeBandType,
                              newChargeBandType),
                           Core.Shared.ErrorLevel.Warning);
                    }
                }
            }

            return result;
        }
Example #6
0
        public RuleResult Evaluate(schemeType scheme, producerType producer, Guid organisationId)
        {
            if (producer.status == statusType.A)
            {
                var existingProducer =
                    querySet.GetProducerForOtherSchemeAndObligationType(producer.registrationNo,
                                                                        scheme.complianceYear, organisationId, producer.obligationType.ToDomainObligationType());

                if (existingProducer != null)
                {
                    string schemeName = "another scheme";
                    if (existingProducer.RegisteredProducer.Scheme != null &&
                        !string.IsNullOrEmpty(existingProducer.RegisteredProducer.Scheme.SchemeName))
                    {
                        schemeName = existingProducer.RegisteredProducer.Scheme.SchemeName;
                    }

                    var errorMessage = string.Format(
                        "{0} {1} is already registered with {2} with obligation type: {3}. Review your file.",
                        producer.GetProducerName(),
                        producer.registrationNo,
                        schemeName,
                        (ObligationType)existingProducer.ObligationType);
                    return(RuleResult.Fail(errorMessage));
                }

                return(RuleResult.Pass());
            }

            return(RuleResult.Pass());
        }
        public async void GetProducerChargeBand_GivenPreviousAmendmentChargeAndChargeQualifies_EnvironmentAgencyProducerChargeWithZeroAmountShouldBeReturned()
        {
            var schemeType = new schemeType()
            {
                approvalNo = "app", complianceYear = ComplianceYear.ToString()
            };
            var producerType = new producerType()
            {
                registrationNo = "no", eeePlacedOnMarketBand = eeePlacedOnMarketBandType.Morethanorequalto5TEEEplacedonmarket
            };
            var producerCharge = new ProducerCharge()
            {
                ChargeBandAmount = new ChargeBandAmount(Guid.NewGuid(), ChargeBand.A, 0)
            };

            A.CallTo(() => registeredProducerDataAccess.GetProducerRegistration(producerType.registrationNo, ComplianceYear, schemeType.approvalNo))
            .Returns(RegisteredProducer());
            A.CallTo(() => environmentAgencyProducerChargeBandCalculator.GetProducerChargeBand(schemeType, producerType)).Returns(producerCharge);
            A.CallTo(() => registeredProducerDataAccess.HasPreviousAmendmentCharge(A <string> ._, A <int> ._, A <string> ._)).Returns(true);

            var result = await calculator.GetProducerChargeBand(schemeType, producerType);

            Assert.Equal(result.ChargeBandAmount, producerCharge.ChargeBandAmount);
            Assert.Equal(result.Amount, 0);
        }
        ProducerRegisteredMatchesComplianceYearAndObligationType_ButRegistrationNumberIsNullOrEmpty_ValidationSucceeds
            (string registrationNumber)
        {
            const string             complianceYear = "2016";
            const obligationTypeType obligationType = obligationTypeType.B2B;

            A.CallTo(() => producerQuerySet.GetProducerForOtherSchemeAndObligationType(A <string> ._, A <string> ._, A <Guid> ._, A <ObligationType> ._))
            .Returns(FakeProducer.Create(obligationType.ToDomainObligationType(), registrationNumber));

            producerType producer = new producerType()
            {
                tradingName      = "Test Trader",
                obligationType   = obligationType,
                producerBusiness = new producerBusinessType
                {
                    Item = new partnershipType
                    {
                        partnershipName = "New Producer Name"
                    }
                }
            };

            schemeType scheme = new schemeType()
            {
                complianceYear = complianceYear,
                producerList   = new[]
                {
                    producer
                }
            };
            var result = Rule().Evaluate(scheme, producer, A.Dummy <Guid>());

            Assert.True(result.IsValid);
        }
Example #9
0
        private void SetupSchemeTypeComplianceYear()
        {
            var schemeType = new schemeType()
            {
                complianceYear = "2019"
            };

            A.CallTo(() => xmlConverter.Deserialize <schemeType>(A <System.Xml.Linq.XDocument> ._)).Returns(schemeType);
        }
Example #10
0
        public void TwoProducersWithDifferentRegistrationNumbers_ValidationSucceeds()
        {
            var scheme = new schemeType
            {
                producerList = ProducersWithRegistrationNumbers("ABC12345", "XYZ54321").ToArray()
            };

            var result = Rule().Evaluate(scheme);

            Assert.True(result.All(r => r.IsValid));
        }
        public void SetOfEmptyRegistrationNumbers_ValidationSucceeds()
        {
            var scheme = new schemeType
            {
                producerList = ProducersWithRegistrationNumbers(string.Empty, string.Empty)
            };

            var results = Rule().Evaluate(scheme);

            Assert.True(results.All(r => r.IsValid));
        }
        public void ProducerWithoutProducerName_ValidationSucceeds(string producerName)
        {
            var scheme = new schemeType
            {
                producerList = ProducersWithProducerNames(producerName)
            };

            var results = Rule().Evaluate(scheme);

            Assert.True(results.All(r => r.IsValid));
        }
        private long ExpectedSeedAfterThisXml(string xml, long initialSeed)
        {
            schemeType parsedXml    = ParseXml(xml);
            uint       expectedSeed = (uint)initialSeed;

            for (int ii = 0; ii < parsedXml.producerList.Count(p => p.status == statusType.I); ii++)
            {
                expectedSeed = new PrnAsComponents(expectedSeed + 1).ToSeedValue();
            }
            return(expectedSeed);
        }
        public ProducerCharge GetProducerChargeBand(schemeType scheme, producerType producer, MemberUpload upload, string name)
        {
            var calculator = chargeChargeBandCalculators.FirstOrDefault(c => c.IsMatch(scheme, producer, upload, name));

            if (calculator == null)
            {
                throw new ApplicationException(string.Format("No charge band calculator found for scheme {0} and producer {1}", scheme.approvalNo, producer.tradingName));
            }

            return(calculator.GetProducerChargeBand(scheme, producer, upload));
        }
        public void TwoProducersWithDifferentProducerNames_ValidationSucceeds()
        {
            var scheme = new schemeType
            {
                producerList = ProducersWithProducerNames("First Producer Name", "Second Producer Name")
            };

            var results = Rule().Evaluate(scheme);

            Assert.True(results.All(r => r.IsValid));
        }
        public void ProducerWithoutProducerName_ValidationSucceeds(string producerName)
        {
            var scheme = new schemeType
            {
                producerList = ProducersWithProducerNames(producerName)
            };

            var results = Rule().Evaluate(scheme);

            Assert.True(results.All(r => r.IsValid));
        }
        public void TwoProducersWithDifferentProducerNames_ValidationSucceeds()
        {
            var scheme = new schemeType
            {
                producerList = ProducersWithProducerNames("First Producer Name", "Second Producer Name")
            };

            var results = Rule().Evaluate(scheme);

            Assert.True(results.All(r => r.IsValid));
        }
Example #18
0
        public void SetOfEmptyRegistrationNumbers_ValidationSucceeds()
        {
            var scheme = new schemeType
            {
                producerList = ProducersWithRegistrationNumbers(string.Empty, string.Empty)
            };

            var results = Rule().Evaluate(scheme);

            Assert.True(results.All(r => r.IsValid));
        }
        public void TwoProducersWithDifferentRegistrationNumbers_ValidationSucceeds()
        {
            var scheme = new schemeType
            {
                producerList = ProducersWithRegistrationNumbers("ABC12345", "XYZ54321").ToArray()
            };

            var result = Rule().Evaluate(scheme);

            Assert.True(result.All(r => r.IsValid));
        }
Example #20
0
        public void IsMatch_GivenProducerIsAmendment_FalseShouldBeReturned()
        {
            var scheme = new schemeType()
            {
                complianceYear = "2019"
            };
            var producer = new producerType {
                status = statusType.A
            };

            var result = producerChargeBandCalculator.IsMatch(scheme, producer);

            Assert.False(result);
        }
Example #21
0
        public void IsMatch_GivenSchemeIs2018OrBeforeAndProducerInsert_FalseShouldBeReturned(string year)
        {
            var scheme = new schemeType()
            {
                complianceYear = year
            };
            var producer = new producerType {
                status = statusType.I
            };

            var result = environmentAgencyProducerChargeBandCalculator.IsMatch(scheme, producer);

            Assert.False(result);
        }
        public RuleResult Evaluate(schemeType scheme, Guid organisationId)
        {
            var approvalNumber = schemeQuerySet.GetSchemeApprovalNumberByOrganisationId(organisationId);
            if (!string.Equals(approvalNumber, scheme.approvalNo, StringComparison.InvariantCultureIgnoreCase))
            {
                return
                    RuleResult.Fail(
                        string.Format(
                            "The PCS approval number {0} you have provided does not match with the PCS. Review the PCS approval number.",
                            scheme.approvalNo));
            }

            return RuleResult.Pass();
        }
Example #23
0
        public void IsMatch_GivenSchemeIsPost2018_FalseShouldBeReturned(string year)
        {
            var scheme = new schemeType()
            {
                complianceYear = year
            };
            var producer = new producerType {
                status = statusType.I
            };

            var result = producerChargeBandCalculator.IsMatch(scheme, producer);

            Assert.False(result);
        }
        public void IsMatch_GivenProducerIsInsert_FalseShouldBeReturned()
        {
            var producer = new producerType()
            {
                status = statusType.I
            };
            var schemeType = new schemeType()
            {
                approvalNo = "app", complianceYear = ComplianceYear.ToString()
            };
            var result = calculator.IsMatch(schemeType, producer);

            Assert.False(result);
        }
Example #25
0
            public RuleResult Evaluate(ChargeBand producerChargeBand, statusType producerStatus = statusType.A)
            {
                var producer = new producerType()
                {
                    status = producerStatus
                };

                var scheme = new schemeType()
                {
                    complianceYear = "2016"
                };

                return(producerChargeBandChange.Evaluate(scheme, producer, A.Dummy <Guid>()));
            }
Example #26
0
        public void DuplicateRegistrationNumbers_ValidationFails_IncludesRegistraionNumberInMessage_AndErrorLevelIsError()
        {
            const string registrationNumber = "ABC12345";
            var          scheme             = new schemeType
            {
                producerList = ProducersWithRegistrationNumbers(registrationNumber, registrationNumber)
            };

            var results = Rule().Evaluate(scheme);

            var duplicate = results.Single(r => !r.IsValid);

            Assert.Contains(registrationNumber, duplicate.Message);
            Assert.Equal(ErrorLevel.Error, duplicate.ErrorLevel);
        }
Example #27
0
        public RuleResult Evaluate(schemeType scheme, Guid organisationId)
        {
            var approvalNumber = schemeQuerySet.GetSchemeApprovalNumberByOrganisationId(organisationId);

            if (!string.Equals(approvalNumber, scheme.approvalNo, StringComparison.InvariantCultureIgnoreCase))
            {
                return
                    (RuleResult.Fail(
                         string.Format(
                             "The PCS approval number {0} you have provided does not match with the PCS you are logged in for. Review the PCS approval number.",
                             scheme.approvalNo)));
            }

            return(RuleResult.Pass());
        }
        public void SetOfDuplicateProducerNames_ValidationFails_IncludesProducerNameInMessage_AndErrorLevelIsError()
        {
            const string producerName = "Producer Name";
            var          scheme       = new schemeType
            {
                producerList = ProducersWithProducerNames(producerName, producerName)
            };

            var result = Rule().Evaluate(scheme);

            var invalidResult = result.Single(r => !r.IsValid);

            Assert.Contains(producerName, invalidResult.Message);
            Assert.Equal(ErrorLevel.Error, invalidResult.ErrorLevel);
        }
        public bool IsMatch(schemeType scheme, producerType producer, MemberUpload upload, string name)
        {
            Log.Information(string.Format("amendment calc {0}", name));
            var year = int.Parse(scheme.complianceYear);
            var previousProducerSubmission =
                registeredProducerDataAccess.GetProducerRegistrationForInsert(producer.registrationNo, year, scheme.approvalNo, upload, name, producer);

            var result = producer.status == statusType.A && (previousProducerSubmission != null);

            if (result)
            {
                Log.Information(string.Format("amendment calc {0}", name));
            }
            return(result);
        }
        public void DuplicateRegistrationNumbers_ValidationFails_IncludesRegistraionNumberInMessage_AndErrorLevelIsError()
        {
            const string registrationNumber = "ABC12345";
            var scheme = new schemeType
            {
                producerList = ProducersWithRegistrationNumbers(registrationNumber, registrationNumber)
            };

            var results = Rule().Evaluate(scheme);

            var duplicate = results.Single(r => !r.IsValid);

            Assert.Contains(registrationNumber, duplicate.Message);
            Assert.Equal(ErrorLevel.Error, duplicate.ErrorLevel);
        }
        public void SetOfDuplicateProducerNames_ValidationFails_IncludesProducerNameInMessage_AndErrorLevelIsError()
        {
            const string producerName = "Producer Name";
            var scheme = new schemeType
            {
                producerList = ProducersWithProducerNames(producerName, producerName)
            };

            var result = Rule().Evaluate(scheme);

            var invalidResult = result.Single(r => !r.IsValid);

            Assert.Contains(producerName, invalidResult.Message);
            Assert.Equal(ErrorLevel.Error, invalidResult.ErrorLevel);
        }
Example #32
0
        public void SchemeApprovalNumber_MatchesApprovalNumberinXML_ValidationSucceeds(string approvalNumber, string existingApprovalNumber)
        {
            var organisationId = Guid.NewGuid();
            var scheme         = new schemeType
            {
                approvalNo = approvalNumber,
            };

            A.CallTo(() => schemeQuerySet.GetSchemeApprovalNumberByOrganisationId(organisationId))
            .Returns(existingApprovalNumber);

            var result = Rule().Evaluate(scheme, organisationId);

            Assert.True(result.IsValid);
        }
        public async void GetProducerChargeBand_GivenProducerSubmission_PreviousAmendmentChargeShouldBeRetrieved()
        {
            var schemeType = new schemeType()
            {
                approvalNo = "app", complianceYear = ComplianceYear.ToString()
            };
            var producerType = new producerType()
            {
                registrationNo = "no"
            };

            await calculator.GetProducerChargeBand(schemeType, producerType);

            A.CallTo(() => registeredProducerDataAccess.HasPreviousAmendmentCharge(producerType.registrationNo, ComplianceYear, schemeType.approvalNo))
            .MustHaveHappened(Repeated.Exactly.Once);
        }
        public async void GetProducerChargeBand_GivenProducerSubmission_EnvironmentAgencyCalculatorChargeBandShouldBeRetrieved()
        {
            var schemeType = new schemeType()
            {
                approvalNo = "app", complianceYear = ComplianceYear.ToString()
            };
            var producerType = new producerType()
            {
                registrationNo = "no"
            };

            await calculator.GetProducerChargeBand(schemeType, producerType);

            A.CallTo(() => environmentAgencyProducerChargeBandCalculator.GetProducerChargeBand(schemeType, producerType))
            .MustHaveHappened(Repeated.Exactly.Once);
        }
Example #35
0
        public void IsMatch_Amendment_NoPreviousSubmission_TrueShouldBeReturned()
        {
            var scheme = new schemeType()
            {
                complianceYear = "2020"
            };
            var producerType = new producerType {
                status = statusType.A
            };

            A.CallTo(() => registeredProducerDataAccess.GetProducerRegistration(A <string> ._, A <int> ._, A <string> ._)).Returns((RegisteredProducer)null);

            var result = environmentAgencyProducerChargeBandCalculator.IsMatch(scheme, producerType);

            Assert.True(result);
        }
        public void IsMatch_GivenProducerIsInsertAndPreviousSubmissionExists_FalseShouldBeReturned()
        {
            var producer = new producerType()
            {
                status = statusType.I
            };
            var schemeType = new schemeType()
            {
                approvalNo = "app", complianceYear = ComplianceYear.ToString()
            };
            var result = calculator.IsMatch(schemeType, producer);

            A.CallTo(() => registeredProducerDataAccess.GetProducerRegistration(A <string> ._, A <int> ._, A <string> ._))
            .Returns((RegisteredProducer)null);

            Assert.False(result);
        }
Example #37
0
        public void IsMatch_Amendment_HasPreviousSubmission_FalseShouldBeReturned()
        {
            var scheme = new schemeType()
            {
                complianceYear = "2020"
            };
            var producerType = new producerType {
                status = statusType.A
            };
            var registeredProducer = new RegisteredProducer(A.Dummy <string>(), A.Dummy <int>(), A.Dummy <Scheme>());

            A.CallTo(() => registeredProducerDataAccess.GetProducerRegistration("ABC", 2020, "ABC/WWW"))
            .Returns(registeredProducer);

            var result = environmentAgencyProducerChargeBandCalculator.IsMatch(scheme, producerType);

            Assert.False(result);
        }
Example #38
0
            public async Task <IEnumerable <ProducerSubmission> > InvokeGenerateProducerData(int numberOfProducers)
            {
                var producers = new List <producerType>();

                for (int i = 0; i < numberOfProducers; i++)
                {
                    GeneratedPrns.Enqueue("TestPrn" + i.ToString());
                    producers.Add(CreateProducer());
                }

                var scheme = new schemeType();

                scheme.producerList = producers.ToArray();

                var generateFromXml = new GenerateFromXml(XmlConverter, DataAccess);

                return(await generateFromXml.GenerateProducerData(scheme, MemberUpload, ProducerCharges));
            }
        private schemeType SchemeWithXProducers(int numberOfProducers)
        {
            var producers = new List <producerType>();

            for (int i = 0; i < numberOfProducers; i++)
            {
                producers.Add(new producerType());
            }

            var scheme = new schemeType
            {
                approvalNo     = "WEE/AA0001YZ/SCH",
                complianceYear = "2016",
                producerList   = producers.ToArray()
            };

            return(scheme);
        }
        public void DeserliazeXml_RemovesWhiteSpaceBeforeChangingEmptyStringsToNull()
        {
            var tradingName = string.Empty;

            var deserializedXml = new schemeType()
            {
                tradingName = tradingName
            };

            A.CallTo(() => deserializer.Deserialize<schemeType>(A<XDocument>._))
                .Returns(deserializedXml);

            A.CallTo(() => whiteSpaceCollapser.Collapse(A<schemeType>._))
                .Invokes(st => tradingName = ((schemeType)st.Arguments[0]).tradingName);

            var result = XmlConverter().Deserialize<schemeType>(A.Dummy<XDocument>());

            Assert.NotEqual(tradingName, result.tradingName);
        }
            ProducerAlreadyRegisteredForSameComplianceYearAndObligationType_ValidationFails_AndMessageIncludesPrnAndObligationType_AndErrorLevelIsError
            (obligationTypeType existingObligationType, obligationTypeType xmlObligationType)
        {
            var schemeId = Guid.NewGuid();

            A.CallTo(() => producerQuerySet.GetProducerForOtherSchemeAndObligationType(A<string>._, A<string>._, schemeId, A<ObligationType>._))
                .Returns(FakeProducer.Create(existingObligationType.ToDomainObligationType(), "ABC12345"));

            const string complianceYear = "2016";
            const string registrationNumber = "ABC12345";

            var producer = new producerType()
            {
                tradingName = "Test Trader",
                obligationType = xmlObligationType,
                registrationNo = registrationNumber,
                status = statusType.A,
                producerBusiness = new producerBusinessType
                {
                    Item = new partnershipType
                    {
                        partnershipName = "New Producer Name"
                    }
                }
            };

            schemeType scheme = new schemeType()
            {
                complianceYear = complianceYear,
                producerList = new[]
                    {
                       producer
                    }
            };
            var result = Rule().Evaluate(scheme, producer, schemeId);

            Assert.False(result.IsValid);
            Assert.Contains(registrationNumber, result.Message);
            Assert.Contains(existingObligationType.ToDomainObligationType().ToString(), result.Message);
            Assert.Equal(Core.Shared.ErrorLevel.Error, result.ErrorLevel);
        }
        public void TwoSetsOfDuplicateProducerNames_ValidationFails_IncludesBothProducerNamesInMessages()
        {
            const string firstProducerName = "First Producer Name";
            const string secondProducerName = "Second Producer Name";
            var scheme = new schemeType
            {
                producerList =
                    ProducersWithProducerNames(firstProducerName, firstProducerName, secondProducerName,
                        secondProducerName)
            };

            var results = Rule().Evaluate(scheme);

            var invalidResults = results.Where(r => !r.IsValid);

            var aggregatedErrorMessages =
                invalidResults.Select(r => r.Message).Aggregate((curr, next) => curr + ", " + next);

            Assert.Contains(firstProducerName, aggregatedErrorMessages);
            Assert.Contains(secondProducerName, aggregatedErrorMessages);
        }
        public RuleResult Evaluate(schemeType scheme, producerType producer, Guid organisationId)
        {
            if (producer.status == statusType.A)
            {
                string existingProducerName = string.Empty;

                var existingProducer =
                    producerQuerySet.GetLatestProducerForComplianceYearAndScheme(producer.registrationNo,
                        scheme.complianceYear, organisationId) ??
                    producerQuerySet.GetLatestProducerFromPreviousComplianceYears(producer.registrationNo);

                if (existingProducer != null)
                {
                    existingProducerName = existingProducer.OrganisationName;
                }
                else
                {
                    var existingMigratedProducer = migratedProducerQuerySet.GetMigratedProducer(producer.registrationNo);

                    if (existingMigratedProducer == null)
                    {
                        // Producer doesn't exist so no warning
                        return RuleResult.Pass();
                    }

                    existingProducerName = existingMigratedProducer.ProducerName;
                }

                if (existingProducerName != producer.GetProducerName())
                {
                    var errorMessage = string.Format("The producer name of {0} {1} will change from {0} to {2}.",
                        existingProducerName, producer.registrationNo, producer.GetProducerName());

                    return RuleResult.Fail(errorMessage, Core.Shared.ErrorLevel.Warning);
                }
            }

            return RuleResult.Pass();
        }
        public void TwoSetsOfDuplicateRegistrationNumbers_ValidationFails_IncludesBothRegistrationNumbersInMessages()
        {
            const string firstRegistrationNumber = "ABC12345";
            const string secondRegistrationNumber = "XYZ54321";

            var scheme = new schemeType
            {
                producerList =
                    ProducersWithRegistrationNumbers(firstRegistrationNumber, firstRegistrationNumber,
                        secondRegistrationNumber, secondRegistrationNumber)
            };

            var results = Rule().Evaluate(scheme);

            var invalidResults = results.Where(r => !r.IsValid);

            Assert.Equal(2, invalidResults.Count());

            var aggregatedErrorMessages =
                invalidResults.Select(r => r.Message).Aggregate((curr, next) => curr + ", " + next);

            Assert.Contains(firstRegistrationNumber, aggregatedErrorMessages);
            Assert.Contains(secondRegistrationNumber, aggregatedErrorMessages);
        }
        public IEnumerable<RuleResult> Evaluate(schemeType scheme)
        {
            var duplicateProducerNames = new List<string>();
            foreach (var producer in scheme.producerList)
            {
                if (!string.IsNullOrEmpty(producer.GetProducerName()))
                {
                    var isDuplicate = scheme.producerList
                        .Any(p => p != producer && p.GetProducerName() == producer.GetProducerName());

                    if (isDuplicate && !duplicateProducerNames.Contains(producer.GetProducerName()))
                    {
                        duplicateProducerNames.Add(producer.GetProducerName());
                        yield return
                            RuleResult.Fail(
                                string.Format("{0} can only appear once in your file. Review your file.",
                                    producer.GetProducerName()));
                        continue;
                    }
                }

                yield return RuleResult.Pass();
            }
        }
        public async Task<IEnumerable<RuleResult>> Validate(schemeType scheme, Guid organisationId)
        {
            var result = new List<RuleResult>();

            // Xml validation only
            result.AddRange(duplicateProducerRegistrationNumbers.Evaluate(scheme));
            result.AddRange(duplicateProducerNames.Evaluate(scheme));

            // Now comparing against existing data...
            result.Add(correctSchemeApprovalNumber.Evaluate(scheme, organisationId));

            var producerObligationTypeChange = producerObligationTypeChangeDelegate(organisationId, scheme.complianceYear);

            // Validate producers
            foreach (var producer in scheme.producerList)
            {
                // Xml validation only
                result.Add(amendmentHasNoProducerRegistrationNumber.Evaluate(producer));
                result.Add(insertHasProducerRegistrationNumber.Evaluate(producer));
                result.Add(ukBasedAuthorisedRepresentative.Evaluate(producer));
                result.Add(producerNameWarning.Evaluate(scheme, producer, organisationId));
                result.Add(annualTurnoverMismatch.Evaluate(producer));
                result.Add(ensureAnOverseasProducerIsNotBasedInTheUK.Evaluate(producer));

                // Now comparing against existing data...
                result.Add(producerRegistrationNumberValidity.Evaluate(producer));
                result.Add(producerAlreadyRegistered.Evaluate(scheme, producer, organisationId));
                result.Add(producerNameAlreadyRegistered.Evaluate());
                result.Add(producerChargeBandChangeWarning.Evaluate(scheme, producer, organisationId));
                result.Add(companyAlreadyRegistered.Evaluate(producer));
                result.Add(companyRegistrationNumberChange.Evaluate(producer));
                result.Add(await producerObligationTypeChange.Evaluate(producer));
            }

            return result.Where(r => r != null && !r.IsValid);
        }
        public async Task WhereAllRulesPass_NoRuleResultsShouldBeReturned()
        {
            A.CallTo(() => producerNameWarning.Evaluate(A<schemeType>._, A<producerType>._, A<Guid>._)).Returns(RuleResult.Pass());
            A.CallTo(() => annualTurnoverMismatch.Evaluate(A<producerType>._)).Returns(RuleResult.Pass());
            A.CallTo(() => producerAlreadyRegistered.Evaluate(A<schemeType>._, A<producerType>._, A<Guid>._)).Returns(RuleResult.Pass());
            A.CallTo(() => producerNameAlreadyRegistered.Evaluate()).Returns(RuleResult.Pass());
            A.CallTo(() => duplicateProducerRegistrationNumbers.Evaluate(A<schemeType>._)).Returns(new List<RuleResult> { RuleResult.Pass() });
            A.CallTo(() => duplicateProducerNames.Evaluate(A<schemeType>._)).Returns(new List<RuleResult> { RuleResult.Pass() });
            A.CallTo(() => correctSchemeApprovalNumber.Evaluate(A<schemeType>._, A<Guid>._)).Returns(RuleResult.Pass());
            A.CallTo(() => amendmentHasNoProducerRegistrationNumber.Evaluate(A<producerType>._)).Returns(RuleResult.Pass());
            A.CallTo(() => insertHasProducerRegistrationNumber.Evaluate(A<producerType>._)).Returns(RuleResult.Pass());
            A.CallTo(() => ukBasedAuthorisedRepresentative.Evaluate(A<producerType>._)).Returns(RuleResult.Pass());
            A.CallTo(() => producerRegistrationNumberValidity.Evaluate(A<producerType>._)).Returns(RuleResult.Pass());
            A.CallTo(() => ensureAnOverseasProducerIsNotBasedInTheUK.Evaluate(A<producerType>._)).Returns(RuleResult.Pass());
            A.CallTo(() => producerChargeBandChangeWarning.Evaluate(A<schemeType>._, A<producerType>._, A<Guid>._)).Returns(RuleResult.Pass());
            A.CallTo(() => companyAlreadyRegistered.Evaluate(A<producerType>._)).Returns(RuleResult.Pass());
            A.CallTo(() => companyRegistrationNumberChange.Evaluate(A<producerType>._)).Returns(RuleResult.Pass());
            A.CallTo(() => producerObligationTypeChange.Evaluate(A<producerType>._)).Returns(RuleResult.Pass());

            var scheme = new schemeType
            {
                approvalNo = "WEE/AA0001YZ/SCH",
                complianceYear = "2016",
                producerList = new[]
                {
                    new producerType()
                }
            };

            var schemeId = Guid.NewGuid();

            var result = await XmlBusinessValidator().Validate(scheme, schemeId);

            Assert.Empty(result);
        }
            public async Task<IEnumerable<ProducerSubmission>> InvokeGenerateProducerData(int numberOfProducers)
            {
                var producers = new List<producerType>();
                for (int i = 0; i < numberOfProducers; i++)
                {
                    GeneratedPrns.Enqueue("TestPrn" + i.ToString());
                    producers.Add(CreateProducer());
                }

                var scheme = new schemeType();
                scheme.producerList = producers.ToArray();

                var generateFromXml = new GenerateFromXml(XmlConverter, DataAccess);

                return await generateFromXml.GenerateProducerData(scheme, MemberUpload, ProducerCharges);
            }
        public void ProducerAlreadyRegisteredForSameComplianceYearButObligationTypeDiffers_ValidationSucceeds(
            obligationTypeType existingObligationType, obligationTypeType xmlObligationType)
        {
            A.CallTo(() => producerQuerySet.GetProducerForOtherSchemeAndObligationType(A<string>._, A<string>._, A<Guid>._, A<ObligationType>._))
               .Returns(FakeProducer.Create(existingObligationType.ToDomainObligationType(), "ABC12345"));

            const string complianceYear = "2016";
            const string registrationNumber = "ABC12345";

            producerType producer = new producerType()
            {
                tradingName = "Test Trader",
                obligationType = xmlObligationType,
                registrationNo = registrationNumber,
                status = statusType.I,
                producerBusiness = new producerBusinessType
                {
                    Item = new partnershipType
                    {
                        partnershipName = "New Producer Name"
                    }
                }
            };

            schemeType scheme = new schemeType()
            {
                complianceYear = complianceYear,
                producerList = new[]
                    {
                       producer
                    }
            };
            var result = Rule().Evaluate(scheme, producer, A.Dummy<Guid>());

            Assert.True(result.IsValid);
        }
        public void ProducerRegisteredForSameComplianceYearAndObligationTypeButPartOfSameScheme_ValidationSucceeds()
        {
            const string complianceYear = "2016";
            const string registrationNumber = "ABC12345";
            var organisationId = Guid.NewGuid();
            const obligationTypeType obligationType = obligationTypeType.B2B;

            A.CallTo(() => producerQuerySet.GetProducerForOtherSchemeAndObligationType(A<string>._, A<string>._, A<Guid>._, A<ObligationType>._))
              .Returns(FakeProducer.Create(obligationType.ToDomainObligationType(), "ABC12345", organisationId));

            producerType producer = new producerType()
            {
                tradingName = "Test Trader",
                obligationType = obligationType,
                registrationNo = registrationNumber,
                status = statusType.I,
                producerBusiness = new producerBusinessType
                {
                    Item = new partnershipType
                    {
                        partnershipName = "New Producer Name"
                    }
                }
            };

            schemeType scheme = new schemeType()
            {
                complianceYear = complianceYear,
                approvalNo = "Test approval number 1",
                producerList = new[]
                    {
                       producer
                    }
            };
            var result = Rule().Evaluate(scheme, producer, A.Dummy<Guid>());

            Assert.True(result.IsValid);
        }
            ProducerRegisteredMatchesComplianceYearAndObligationType_ButRegistrationNumberIsNullOrEmpty_ValidationSucceeds
            (string registrationNumber)
        {
            const string complianceYear = "2016";
            const obligationTypeType obligationType = obligationTypeType.B2B;

            A.CallTo(() => producerQuerySet.GetProducerForOtherSchemeAndObligationType(A<string>._, A<string>._, A<Guid>._, A<ObligationType>._))
              .Returns(FakeProducer.Create(obligationType.ToDomainObligationType(), registrationNumber));

            producerType producer = new producerType()
            {
                tradingName = "Test Trader",
                obligationType = obligationType,
                producerBusiness = new producerBusinessType
                {
                    Item = new partnershipType
                    {
                        partnershipName = "New Producer Name"
                    }
                }
            };

            schemeType scheme = new schemeType()
            {
                complianceYear = complianceYear,
                producerList = new[]
                    {
                       producer
                    }
            };
            var result = Rule().Evaluate(scheme, producer, A.Dummy<Guid>());

            Assert.True(result.IsValid);
        }
        public async Task<IEnumerable<ProducerSubmission>> GenerateProducerData(schemeType scheme, MemberUpload memberUpload, Dictionary<string, ProducerCharge> producerCharges)
        {
            if (memberUpload.ComplianceYear == null)
            {
                string errorMessage = "Producers cannot be generated for a member upload "
                    + "that does not have a compliance year.";
                throw new InvalidOperationException(errorMessage);
            }

            List<ProducerSubmission> producers = new List<ProducerSubmission>();

            int numberOfPrnsNeeded = scheme.producerList.Count(p => p.status == statusType.I);
            Queue<string> generatedPrns = await dataAccess.ComputePrns(numberOfPrnsNeeded);

            foreach (producerType producerData in scheme.producerList)
            {
                var producerName = producerData.GetProducerName();

                if (producerCharges == null)
                {
                    throw new ApplicationException("No charges have been supplied");
                }
                if (!producerCharges.ContainsKey(producerName))
                {
                    throw new ApplicationException(string.Format("No charges have been supplied for the {0}.", producerName));
                }
                var chargeBandAmount = producerCharges[producerName].ChargeBandAmount;
                var chargeThisUpdate = producerCharges[producerName].Amount;

                List<BrandName> brandNames = producerData.producerBrandNames.Select(name => new BrandName(name)).ToList();

                List<SICCode> codes = producerData.SICCodeList.Select(name => new SICCode(name)).ToList();

                ProducerBusiness producerBusiness = await SetProducerBusiness(producerData.producerBusiness);

                AuthorisedRepresentative authorisedRepresentative = await SetAuthorisedRepresentative(producerData.authorisedRepresentative);

                EEEPlacedOnMarketBandType eeebandType = Enumeration.FromValue<EEEPlacedOnMarketBandType>((int)producerData.eeePlacedOnMarketBand);

                SellingTechniqueType sellingTechniqueType = Enumeration.FromValue<SellingTechniqueType>((int)producerData.sellingTechnique);

                ObligationType obligationType = producerData.obligationType.ToDomainObligationType();

                AnnualTurnOverBandType annualturnoverType = Enumeration.FromValue<AnnualTurnOverBandType>((int)producerData.annualTurnoverBand);

                DateTime? ceaseDate = null;
                if (producerData.ceaseToExistDateSpecified)
                {
                    ceaseDate = producerData.ceaseToExistDate;
                }

                RegisteredProducer registeredProducer = null;

                string producerRegistrationNo;
                switch (producerData.status)
                {
                    case statusType.I:
                    producerRegistrationNo = generatedPrns.Dequeue();
                        break;

                    case statusType.A:
                        producerRegistrationNo = producerData.registrationNo;

                        await EnsureProducerRegistrationNumberExists(producerRegistrationNo);

                        registeredProducer = await dataAccess.FetchRegisteredProducerOrDefault(
                            producerRegistrationNo,
                            memberUpload.ComplianceYear.Value,
                            memberUpload.Scheme.Id);
                        break;

                    default:
                        throw new NotSupportedException();
                }

                if (registeredProducer == null)
                {
                    registeredProducer = new RegisteredProducer(
                        producerRegistrationNo,
                        memberUpload.ComplianceYear.Value,
                        memberUpload.Scheme);
                }

                ProducerSubmission producer = new ProducerSubmission(
                    registeredProducer,
                    memberUpload,
                    producerBusiness,
                    authorisedRepresentative,
                    SystemTime.UtcNow,
                    producerData.annualTurnover,
                    producerData.VATRegistered,
                    ceaseDate,
                    producerData.tradingName,
                    eeebandType,
                    sellingTechniqueType,
                    obligationType,
                    annualturnoverType,
                    brandNames,
                    codes,
                    chargeBandAmount,
                    chargeThisUpdate);

                // modify producer data
                switch (producerData.status)
                {
                    case statusType.A:

                        if (registeredProducer.CurrentSubmission == null)
                        {
                            producers.Add(producer);
                        }
                        else
                        {
                            if (!registeredProducer.CurrentSubmission.Equals(producer))
                            {
                                producers.Add(producer);
                            }
                            else
                            {
                                /*
                                 * The producer's details are the same as the current submission for this
                                 * registration so we don't need to update them.
                                 */
                            }
                        }
                        break;

                    case statusType.I:
                        producers.Add(producer);
                        break;
                }
            }

            return producers;
        }
        private schemeType SchemeWithXProducers(int numberOfProducers)
        {
            var producers = new List<producerType>();
            for (int i = 0; i < numberOfProducers; i++)
            {
                producers.Add(new producerType());
            }

            var scheme = new schemeType
            {
                approvalNo = "WEE/AA0001YZ/SCH",
                complianceYear = "2016",
                producerList = producers.ToArray()
            };

            return scheme;
        }
            public RuleResult Evaluate(ChargeBand producerChargeBand, statusType producerStatus = statusType.A)
            {
                var producer = new producerType()
                {
                    status = producerStatus
                };

                var scheme = new schemeType()
                {
                    complianceYear = "2016"
                };

                A.CallTo(() => ProducerChargeBandCalculator.GetProducerChargeBand(A<annualTurnoverBandType>._, A<bool>._, A<eeePlacedOnMarketBandType>._))
                    .Returns(producerChargeBand);

                return producerChargeBandChange.Evaluate(scheme, producer, A.Dummy<Guid>());
            }
        public void GenerateMemberUpload_ReturnsNewMemberUpload_WithCorrectValues()
        {
            var message = new ProcessXmlFile(
                new Guid("4CAD6CA3-E4E7-4D1A-BAAB-8C454EECF109"),
                new byte[1],
                "File name");

            Scheme scheme = A.Dummy<Scheme>();

            var errors = new List<MemberUploadError>
                {
                    new MemberUploadError(ErrorLevel.Error, UploadErrorType.Business, "Some schema error")
                };

            var builder = new GenerateFromXmlBuilder();

            string xml = "Test xml contents";
            A.CallTo(() => builder.XmlConverter.XmlToUtf8String(A<byte[]>._)).Returns(xml);

            schemeType xmlScheme = new schemeType() { complianceYear = "2015" };
            A.CallTo(() => builder.XmlConverter.Deserialize<schemeType>(A<XDocument>._)).Returns(xmlScheme);

            var result = builder.Build().GenerateMemberUpload(message, errors, 1000, scheme);

            Assert.Equal(new Guid("4CAD6CA3-E4E7-4D1A-BAAB-8C454EECF109"), result.OrganisationId);
            Assert.Equal(xml, result.RawData.Data);
            Assert.Equal(errors, result.Errors);
            Assert.Equal(1000, result.TotalCharges);
            Assert.Equal(2015, result.ComplianceYear);
            Assert.Equal(scheme, result.Scheme);
            Assert.Equal("File name", result.FileName);
        }