Exemple #1
0
        // BR1
        public IEnumerable <string> GetRelevantLearners(AppsCoInvestmentILRInfo ilrInfo, AppsCoInvestmentPaymentsInfo paymentsInfo)
        {
            var fm36learners = ilrInfo
                               .Learners?
                               .Where(l =>
                                      l.LearningDeliveries?
                                      .Any(ld => ld.FundModel == 36)
                                      ?? false);

            var pmrLearnRefNumbers = fm36learners
                                     .Where(l =>
                                            l.LearningDeliveries?
                                            .Any(ld => ld.AppFinRecords?.Any(afr => afr.AFinType == "PMR") ?? false)
                                            ?? false)
                                     .Select(l => l.LearnRefNumber).ToList()
                                     ?? Enumerable.Empty <string>();

            var fm36LearnRefNumbers = new HashSet <string>(fm36learners.Select(l => l.LearnRefNumber), StringComparer.OrdinalIgnoreCase);

            var paymentLearnRefNumbers = paymentsInfo
                                         .Payments
                                         .Where(p => p.FundingSource == _fundingSource && fm36LearnRefNumbers.Contains(p.LearnerReferenceNumber))
                                         .Select(p => p.LearnerReferenceNumber).ToList();

            return(pmrLearnRefNumbers.Union(paymentLearnRefNumbers));
        }
Exemple #2
0
 public bool PMRAppFinRecordFilter(AppsCoInvestmentILRInfo ilrInfo, string learnRefNumber)
 {
     return(ilrInfo
            .Learners?.Any(
                l =>
                l.LearnRefNumber.CaseInsensitiveEquals(learnRefNumber) &&
                (l.LearningDeliveries?.Any(ld =>
                                           ld.AppFinRecords?.Any(afr => afr.AFinType.CaseInsensitiveEquals(Generics.PMR))
                                           ?? false)
                 ?? false))
            ?? false);
 }
        public IReadOnlyList <LearnerLevelViewModel> BuildLearnerLevelViewModelList(
            int ukprn,
            AppsMonthlyPaymentILRInfo appsMonthlyPaymentIlrInfo,
            AppsCoInvestmentILRInfo appsCoInvestmentIlrInfo,
            LearnerLevelViewDASDataLockInfo learnerLevelViewDASDataLockInfo,
            LearnerLevelViewHBCPInfo learnerLevelHBCPInfo,
            LearnerLevelViewFM36Info learnerLevelDAsInfo,
            IDictionary <LearnerLevelViewPaymentsKey, List <AppsMonthlyPaymentDasPaymentModel> > paymentsDictionary,
            IDictionary <string, List <AECApprenticeshipPriceEpisodePeriodisedValuesInfo> > aECPriceEpisodeDictionary,
            IDictionary <string, List <AECLearningDeliveryPeriodisedValuesInfo> > aECLearningDeliveryDictionary,
            IDictionary <long, string> employerNameDictionary,
            int returnPeriod)
        {
            // cache the passed in data for use in the private 'Get' methods
            _appsReturnPeriod = returnPeriod;

            // this variable is the final report and is the return value of this method.
            List <LearnerLevelViewModel> learnerLevelViewModelList = null;

            try
            {
                // Lookup for employer IDs to employer name
                IDictionary <int, string> employerNamesToIDs = new Dictionary <int, string>();

                // Union the keys from the datasets being used to source the report
                var unionedKeys = UnionKeys(paymentsDictionary.Keys, aECPriceEpisodeDictionary.Keys, aECLearningDeliveryDictionary.Keys);

                // Populate the learner list using the ILR query first
                learnerLevelViewModelList = unionedKeys
                                            .OrderBy(o => o.LearnerReferenceNumber)
                                            .ThenBy(o => o.PaymentFundingLineType)
                                            .Select(record =>
                {
                    var reportRecord = new LearnerLevelViewModel()
                    {
                        Ukprn = ukprn,
                        PaymentLearnerReferenceNumber = record.LearnerReferenceNumber,
                        PaymentFundingLineType        = record.PaymentFundingLineType
                    };

                    // Extract ILR info
                    var ilrRecord = appsMonthlyPaymentIlrInfo.Learners.FirstOrDefault(p => p.LearnRefNumber == reportRecord.PaymentLearnerReferenceNumber);
                    if (ilrRecord != null)
                    {
                        reportRecord.FamilyName = ilrRecord.FamilyName;
                        reportRecord.GivenNames = ilrRecord.GivenNames;
                        reportRecord.PaymentUniqueLearnerNumber = ilrRecord.UniqueLearnerNumber;
                        if ((ilrRecord.LearnerEmploymentStatus != null) && (ilrRecord.LearnerEmploymentStatus.Count > 0))
                        {
                            reportRecord.LearnerEmploymentStatusEmployerId = ilrRecord.LearnerEmploymentStatus.Where(les => les?.Ukprn == ukprn &&
                                                                                                                     les.LearnRefNumber.CaseInsensitiveEquals(reportRecord.PaymentLearnerReferenceNumber) &&
                                                                                                                     les?.EmpStat == 10)
                                                                             .OrderByDescending(les => les?.DateEmpStatApp)
                                                                             .FirstOrDefault()?.EmpdId;
                        }
                    }

                    if (paymentsDictionary.TryGetValue(new LearnerLevelViewPaymentsKey(reportRecord.PaymentLearnerReferenceNumber, reportRecord.PaymentFundingLineType), out List <AppsMonthlyPaymentDasPaymentModel> paymentValues))
                    {
                        // Assign the amounts
                        reportRecord.PlannedPaymentsToYouToDate = paymentValues.Where(p => PeriodESFAPlannedPaymentsFSTypePredicateToPeriod(p, _appsReturnPeriod) ||
                                                                                      PeriodESFAPlannedPaymentsTTTypePredicateToPeriod(p, _appsReturnPeriod) ||
                                                                                      PeriodESFAPlannedPaymentsNonZPTypePredicateToPeriod(p, _appsReturnPeriod)).Sum(c => c.Amount ?? 0m);

                        reportRecord.ESFAPlannedPaymentsThisPeriod = paymentValues.Where(p => PeriodESFAPlannedPaymentsFSTypePredicate(p, _appsReturnPeriod) ||
                                                                                         PeriodESFAPlannedPaymentsTTTypePredicate(p, _appsReturnPeriod) ||
                                                                                         PeriodESFAPlannedPaymentsNonZPTypePredicate(p, _appsReturnPeriod)).Sum(c => c.Amount ?? 0m);

                        reportRecord.CoInvestmentPaymentsToCollectThisPeriod = paymentValues.Where(p => PeriodCoInvestmentDueFromEmployerPaymentsTypePredicate(p, _appsReturnPeriod)).Sum(c => c.Amount ?? 0m);

                        // NOTE: Additional earigns calc required for this field
                        reportRecord.CoInvestmentOutstandingFromEmplToDate = paymentValues.Where(p => PeriodCoInvestmentDueFromEmployerPaymentsTypePredicateToPeriod(p, _appsReturnPeriod)).Sum(c => c.Amount ?? 0m);

                        // Pull across the ULN if it's not already there (we can pick the first record as the set is matched on learner ref so all ULNs in it will be the same)
                        reportRecord.PaymentUniqueLearnerNumber = paymentValues.FirstOrDefault()?.LearnerUln;

                        // Extract company name
                        string employerName;
                        if ((employerNameDictionary != null) && employerNameDictionary.TryGetValue(paymentValues.FirstOrDefault().ApprenticeshipId ?? 0, out employerName))
                        {
                            reportRecord.EmployerName = employerName;
                            if ((reportRecord.LearnerEmploymentStatusEmployerId != null) && !employerNamesToIDs.ContainsKey(reportRecord.LearnerEmploymentStatusEmployerId ?? 0))
                            {
                                employerNamesToIDs.Add(new KeyValuePair <int, string>(reportRecord.LearnerEmploymentStatusEmployerId ?? 0, reportRecord.EmployerName));
                            }
                        }
                        else
                        {
                            reportRecord.EmployerName = string.Empty;
                        }
                    }

                    if (appsCoInvestmentIlrInfo != null)
                    {
                        var ilrInfo = appsCoInvestmentIlrInfo.Learners?
                                      .FirstOrDefault(l => l.LearnRefNumber.CaseInsensitiveEquals(reportRecord.PaymentLearnerReferenceNumber));

                        if (ilrInfo != null)
                        {
                            var learningDeliveries = ilrInfo.LearningDeliveries.Where(p => p.LearnRefNumber == reportRecord.PaymentLearnerReferenceNumber);
                            if ((learningDeliveries != null) && (learningDeliveries.Count() > 0))
                            {
                                foreach (var learningDelivery in learningDeliveries)
                                {
                                    IReadOnlyCollection <AppFinRecordInfo> currentYearData = learningDelivery.AppFinRecords.Where(x => x.AFinDate >= Generics.BeginningOfYear && x.AFinDate <= Generics.EndOfYear && x.AFinType.CaseInsensitiveEquals("PMR")).ToList();
                                    reportRecord.TotalCoInvestmentCollectedToDate          =
                                        currentYearData.Where(x => x.AFinCode == 1 || x.AFinCode == 2).Sum(x => x.AFinAmount) -
                                        currentYearData.Where(x => x.AFinCode == 3).Sum(x => x.AFinAmount);
                                }
                            }
                        }
                    }

                    // Work out total earnings
                    aECLearningDeliveryDictionary.TryGetValue(reportRecord.PaymentLearnerReferenceNumber, out List <AECLearningDeliveryPeriodisedValuesInfo> ldLearner);
                    aECPriceEpisodeDictionary.TryGetValue(reportRecord.PaymentLearnerReferenceNumber, out List <AECApprenticeshipPriceEpisodePeriodisedValuesInfo> peLearner);

                    reportRecord.TotalEarningsToDate = CalculatePriceEpisodeEarningsToPeriod(ldLearner, peLearner, true, _appsReturnPeriod, reportRecord) +
                                                       CalculateLearningDeliveryEarningsToPeriod(ldLearner, true, _appsReturnPeriod, reportRecord);

                    reportRecord.TotalEarningsForPeriod = CalculatePriceEpisodeEarningsToPeriod(ldLearner, peLearner, false, _appsReturnPeriod, reportRecord) +
                                                          CalculateLearningDeliveryEarningsToPeriod(ldLearner, false, _appsReturnPeriod, reportRecord);

                    // Get any missing funding line types from earnings
                    if (string.IsNullOrEmpty(reportRecord.PaymentFundingLineType) && learnerLevelDAsInfo != null && learnerLevelDAsInfo.AECPriceEpisodeFLTsInfo != null)
                    {
                        reportRecord.PaymentFundingLineType = learnerLevelDAsInfo.AECPriceEpisodeFLTsInfo.FirstOrDefault(p => p.LearnerReferenceNumber == reportRecord.PaymentLearnerReferenceNumber)?.PaymentFundingLineType;
                    }

                    // Default any null valued records
                    reportRecord.ESFAPlannedPaymentsThisPeriod           = reportRecord.ESFAPlannedPaymentsThisPeriod == null ? 0 : reportRecord.ESFAPlannedPaymentsThisPeriod;
                    reportRecord.PlannedPaymentsToYouToDate              = reportRecord.PlannedPaymentsToYouToDate == null ? 0 : reportRecord.PlannedPaymentsToYouToDate;
                    reportRecord.CoInvestmentOutstandingFromEmplToDate   = reportRecord.CoInvestmentOutstandingFromEmplToDate == null ? 0 : reportRecord.CoInvestmentOutstandingFromEmplToDate;
                    reportRecord.CoInvestmentPaymentsToCollectThisPeriod = reportRecord.CoInvestmentPaymentsToCollectThisPeriod == null ? 0 : reportRecord.CoInvestmentPaymentsToCollectThisPeriod;
                    reportRecord.TotalCoInvestmentCollectedToDate        = reportRecord.TotalCoInvestmentCollectedToDate == null ? 0 : reportRecord.TotalCoInvestmentCollectedToDate;

                    // Work out calculated fields
                    // Issues amount - how much the gap is between what the provider earnt and the payments the ESFA/Employer were planning to give them
                    // Following BR2 - if payments are => earnings, issues amount should be zero
                    if ((reportRecord.ESFAPlannedPaymentsThisPeriod + reportRecord.CoInvestmentPaymentsToCollectThisPeriod) >= reportRecord.TotalEarningsForPeriod)
                    {
                        reportRecord.IssuesAmount = 0;
                    }
                    else
                    {
                        reportRecord.IssuesAmount = (reportRecord.TotalEarningsForPeriod
                                                     - reportRecord.ESFAPlannedPaymentsThisPeriod
                                                     - reportRecord.CoInvestmentPaymentsToCollectThisPeriod) * -1;
                    }

                    // Work out what is remaining from employer by subtracting what they a have paid so far from their calculated payments.
                    reportRecord.CoInvestmentOutstandingFromEmplToDate = reportRecord.CoInvestmentOutstandingFromEmplToDate - reportRecord.TotalCoInvestmentCollectedToDate;

                    // Issues for non-payment - worked out in order of priority.
                    // Work out issues (Other) (NOTE: Do this first as lowest priority)
                    if (reportRecord.TotalEarningsForPeriod > reportRecord.CoInvestmentPaymentsToCollectThisPeriod +
                        reportRecord.ESFAPlannedPaymentsThisPeriod)
                    {
                        reportRecord.ReasonForIssues = Reports.LearnerLevelViewReport.ReasonForIssues_Other;
                    }

                    // Work out issues (HBCP)
                    if ((learnerLevelHBCPInfo != null) &&
                        learnerLevelHBCPInfo.HBCPModels.Any(p => p.LearnerReferenceNumber == reportRecord.PaymentLearnerReferenceNumber &&
                                                            p.NonPaymentReason == 0 &&
                                                            p.DeliveryPeriod == _appsReturnPeriod))
                    {
                        reportRecord.ReasonForIssues = Reports.LearnerLevelViewReport.ReasonForIssues_CompletionHoldbackPayment;
                    }

                    // Work out reason for issues (Clawback)
                    if (reportRecord.ESFAPlannedPaymentsThisPeriod < 0)
                    {
                        reportRecord.ReasonForIssues = Reports.LearnerLevelViewReport.ReasonForIssues_Clawback;
                    }

                    // NOTE: As per WI93411, a level of rounding is required before the comparisions can be performed
                    if ((reportRecord.TotalEarningsForPeriod > reportRecord.ESFAPlannedPaymentsThisPeriod +
                         reportRecord.CoInvestmentPaymentsToCollectThisPeriod) &&
                        (decimal.Round(reportRecord.TotalEarningsToDate ?? 0, 2) == decimal.Round((reportRecord.PlannedPaymentsToYouToDate ?? 0) +
                                                                                                  (reportRecord.TotalCoInvestmentCollectedToDate ?? 0) +
                                                                                                  (reportRecord.CoInvestmentOutstandingFromEmplToDate ?? 0), 2)))
                    {
                        reportRecord.ReasonForIssues = Reports.LearnerLevelViewReport.ReasonForIssues_Clawback;
                    }

                    // If the reason for issue is datalock then we need to set the rule description
                    if ((learnerLevelViewDASDataLockInfo != null) && (learnerLevelViewDASDataLockInfo.DASDataLocks != null))
                    {
                        var datalock = learnerLevelViewDASDataLockInfo.DASDataLocks
                                       .FirstOrDefault(x => x.LearnerReferenceNumber == reportRecord.PaymentLearnerReferenceNumber &&
                                                       x.DeliveryPeriod == _appsReturnPeriod);

                        // Check to see if any records returned
                        if (datalock != null)
                        {
                            // Extract data lock info
                            int datalock_rule_id = datalock.DataLockFailureId;

                            // calculate the rule description
                            string datalockValue         = Generics.DLockErrorRuleNamePrefix + datalock_rule_id.ToString("00");
                            reportRecord.ReasonForIssues = datalockValue;
                            reportRecord.RuleDescription = DataLockValidationMessages.Validations.FirstOrDefault(x => x.RuleId.CaseInsensitiveEquals(datalockValue))?.ErrorMessage;
                        }
                    }

                    // Default any null calculated records
                    reportRecord.IssuesAmount    = reportRecord.IssuesAmount == null ? 0 : reportRecord.IssuesAmount;
                    reportRecord.ReasonForIssues = reportRecord.ReasonForIssues == null ? string.Empty : reportRecord.ReasonForIssues;
                    reportRecord.CoInvestmentOutstandingFromEmplToDate = reportRecord.CoInvestmentOutstandingFromEmplToDate == null ? 0 : reportRecord.CoInvestmentOutstandingFromEmplToDate;

                    return(reportRecord);
                }).ToList();

                // Remove the zeroed results
                learnerLevelViewModelList.RemoveAll(p => p.TotalEarningsToDate == 0 && p.PlannedPaymentsToYouToDate == 0 && p.TotalCoInvestmentCollectedToDate == 0 &&
                                                    p.CoInvestmentOutstandingFromEmplToDate == 0 && p.TotalEarningsForPeriod == 0 && p.ESFAPlannedPaymentsThisPeriod == 0 &&
                                                    p.CoInvestmentPaymentsToCollectThisPeriod == 0 && p.IssuesAmount == 0);

                // Set the missing employer names
                foreach (var llvr in learnerLevelViewModelList.Where(w => w.EmployerName == string.Empty || w.EmployerName == null))
                {
                    string employerName;
                    if (employerNamesToIDs.TryGetValue(llvr.LearnerEmploymentStatusEmployerId ?? 0, out employerName))
                    {
                        llvr.EmployerName = employerName;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Failed to Build Learner Level View", ex);
                throw ex;
            }

            return(learnerLevelViewModelList);
        }
Exemple #4
0
        public async Task <AppsCoInvestmentILRInfo> GetILRInfoForAppsCoInvestmentReportAsync(int ukPrn, CancellationToken cancellationToken)
        {
            var appsCoInvestmentIlrInfo = new AppsCoInvestmentILRInfo
            {
                UkPrn    = ukPrn,
                Learners = new List <LearnerInfo>()
            };

            cancellationToken.ThrowIfCancellationRequested();

            List <Learner> learnersList;

            using (var ilrContext = _ilrValidContextFactory())
            {
                learnersList = await ilrContext.Learners
                               .Include(x => x.LearningDeliveries).ThenInclude(y => y.AppFinRecords)
                               .Include(x => x.LearnerEmploymentStatuses)
                               .Where(x => x.UKPRN == ukPrn && x.LearningDeliveries.Any(y => y.FundModel == ApprentishipsFundModel))
                               .ToListAsync(cancellationToken);
            }

            foreach (var learner in learnersList)
            {
                var learnerInfo = new LearnerInfo
                {
                    LearnRefNumber     = learner.LearnRefNumber,
                    LearningDeliveries = learner.LearningDeliveries.Select(x => new LearningDeliveryInfo()
                    {
                        UKPRN          = ukPrn,
                        LearnRefNumber = x.LearnRefNumber,
                        LearnAimRef    = x.LearnAimRef,
                        AimType        = x.AimType,
                        AimSeqNumber   = x.AimSeqNumber,
                        LearnStartDate = x.LearnStartDate,
                        ProgType       = x.ProgType,
                        StdCode        = x.StdCode,
                        FworkCode      = x.FworkCode,
                        PwayCode       = x.PwayCode,
                        SWSupAimId     = x.SWSupAimId,
                        AppFinRecords  = x.AppFinRecords.Select(y => new AppFinRecordInfo()
                        {
                            LearnRefNumber = y.LearnRefNumber,
                            AimSeqNumber   = y.AimSeqNumber,
                            AFinType       = y.AFinType,
                            AFinCode       = y.AFinCode,
                            AFinDate       = y.AFinDate,
                            AFinAmount     = y.AFinAmount
                        }).ToList()
                    }).ToList(),
                    LearnerEmploymentStatus = learner.LearnerEmploymentStatuses.Select(x => new LearnerEmploymentStatusInfo()
                    {
                        LearnRefNumber = x.LearnRefNumber,
                        DateEmpStatApp = x.DateEmpStatApp,
                        EmpId          = x.EmpId
                    }).ToList()
                };
                appsCoInvestmentIlrInfo.Learners.Add(learnerInfo);
            }

            return(appsCoInvestmentIlrInfo);
        }
        public async Task <AppsCoInvestmentILRInfo> GetILRInfoForAppsCoInvestmentReportAsync(int ukPrn, CancellationToken cancellationToken)
        {
            var appsCoInvestmentIlrInfo = new AppsCoInvestmentILRInfo
            {
                UkPrn    = ukPrn,
                Learners = new List <LearnerInfo>()
            };

            cancellationToken.ThrowIfCancellationRequested();

            using (var ilrContext = _ilrValidContextFactory())
            {
                var learners = await ilrContext
                               .Learners
                               .Where(x => x.UKPRN == ukPrn && x.LearningDeliveries.Any(ld => ld.FundModel == 36 && ld.LearnAimRef == "ZPROG001"))
                               .Select(learner =>
                                       new LearnerInfo()
                {
                    LearnRefNumber     = learner.LearnRefNumber,
                    LearningDeliveries = learner
                                         .LearningDeliveries
                                         .Where(ld => ld.FundModel == 36 && ld.LearnAimRef == "ZPROG001")
                                         .Select(x => new LearningDeliveryInfo()
                    {
                        UKPRN          = ukPrn,
                        LearnRefNumber = x.LearnRefNumber,
                        LearnAimRef    = x.LearnAimRef,
                        AimType        = x.AimType,
                        AimSeqNumber   = x.AimSeqNumber,
                        LearnStartDate = x.LearnStartDate,
                        FundModel      = x.FundModel,
                        // Note: Payments default to zero instead of null for no value so we need to cater for that here so that joins work correctly
                        ProgType      = x.ProgType ?? 0,
                        StdCode       = x.StdCode ?? 0,
                        FworkCode     = x.FworkCode ?? 0,
                        PwayCode      = x.PwayCode ?? 0,
                        SWSupAimId    = x.SWSupAimId,
                        AppFinRecords = x.AppFinRecords
                                        .Where(afr => afr.AFinType == "PMR")
                                        .Select(y => new AppFinRecordInfo()
                        {
                            LearnRefNumber = y.LearnRefNumber,
                            AimSeqNumber   = y.AimSeqNumber,
                            AFinType       = y.AFinType,
                            AFinCode       = y.AFinCode,
                            AFinDate       = y.AFinDate,
                            AFinAmount     = y.AFinAmount
                        }).ToList(),
                        LearningDeliveryFAMs = x.LearningDeliveryFAMs
                                               .Where(fam => fam.LearnDelFAMType == "LDM")
                                               .Select(y => new ESFA.DC.ILR2021.DataStore.EF.LearningDeliveryFAM()
                        {
                            UKPRN           = y.UKPRN,
                            LearnRefNumber  = y.LearnRefNumber,
                            AimSeqNumber    = y.AimSeqNumber,
                            LearnDelFAMType = y.LearnDelFAMType,
                            LearnDelFAMCode = y.LearnDelFAMCode
                        }).ToList(),
                    }).ToList(),
                    LearnerEmploymentStatus = learner.LearnerEmploymentStatuses.Select(x => new LearnerEmploymentStatusInfo()
                    {
                        LearnRefNumber = x.LearnRefNumber,
                        DateEmpStatApp = x.DateEmpStatApp,
                        EmpId          = x.EmpId
                    }).ToList()
                }).ToListAsync(cancellationToken);

                appsCoInvestmentIlrInfo.Learners = learners;
            }

            return(appsCoInvestmentIlrInfo);
        }
Exemple #6
0
 // BR2
 public bool FilterReportRows(AppsCoInvestmentPaymentsInfo paymentInfo, AppsCoInvestmentRulebaseInfo rulebaseInfo, AppsCoInvestmentILRInfo ilrInfo, AppsCoInvestmentRecordKey recordKey)
 {
     return
         (EmployerCoInvestmentPaymentFilter(paymentInfo, recordKey.LearnerReferenceNumber) ||
          CompletionPaymentFilter(paymentInfo, recordKey.LearnerReferenceNumber) ||
          PMRAppFinRecordFilter(ilrInfo, recordKey.LearnerReferenceNumber) ||
          NonZeroCompletionEarningsFilter(rulebaseInfo, recordKey.LearnerReferenceNumber));
 }
Exemple #7
0
        public IEnumerable <AppsCoInvestmentContributionsModel> BuildModel(
            AppsCoInvestmentILRInfo appsCoInvestmentIlrInfo,
            AppsCoInvestmentRulebaseInfo appsCoInvestmentRulebaseInfo,
            AppsCoInvestmentPaymentsInfo appsCoInvestmentPaymentsInfo,
            List <AppsCoInvestmentRecordKey> paymentsAppsCoInvestmentUniqueKeys,
            List <AppsCoInvestmentRecordKey> ilrAppsCoInvestmentUniqueKeys,
            IDictionary <long, string> apprenticeshipIdLegalEntityNameDictionary,
            long jobId,
            int ukprn)
        {
            string errorMessage;

            if (appsCoInvestmentIlrInfo == null || appsCoInvestmentIlrInfo.Learners == null)
            {
                errorMessage = "Error: BuildModel() - AppsCoInvestmentILRInfo is null, no data has been retrieved from the ILR1920 data store.";
                _logger.LogInfo(errorMessage, jobIdOverride: jobId);

                throw new Exception(errorMessage);
            }

            if (appsCoInvestmentRulebaseInfo == null)
            {
                errorMessage = "Error: BuildModel() - AppsCoInvestmentRulebaseInfo is null, no data has been retrieved from the ILR1920 data store.";
                _logger.LogInfo(errorMessage, jobIdOverride: jobId);

                throw new Exception(errorMessage);
            }

            if (appsCoInvestmentPaymentsInfo == null)
            {
                errorMessage = "Error: BuildModel() - appsCoInvestmentPaymentsInfo is null, no data has been retrieved from the Payments data store.";
                _logger.LogInfo(errorMessage, jobIdOverride: jobId);

                throw new Exception(errorMessage);
            }

            var paymentsDictionary = BuildPaymentInfoDictionary(appsCoInvestmentPaymentsInfo);
            var learnerDictionary  = BuildLearnerDictionary(appsCoInvestmentIlrInfo);

            var relevantLearnRefNumbers = GetRelevantLearners(appsCoInvestmentIlrInfo, appsCoInvestmentPaymentsInfo).ToList();

            var uniqueKeys = UnionKeys(relevantLearnRefNumbers, ilrAppsCoInvestmentUniqueKeys, paymentsAppsCoInvestmentUniqueKeys).ToList();

            return(uniqueKeys
                   .Where(r => FilterReportRows(appsCoInvestmentPaymentsInfo, appsCoInvestmentRulebaseInfo, appsCoInvestmentIlrInfo, r))
                   .Select(record =>
            {
                var paymentRecords = GetPaymentInfosForRecord(paymentsDictionary, record).ToList();
                var learner = GetLearnerForRecord(learnerDictionary, record);
                var learningDelivery = GetLearningDeliveryForRecord(learner, record);
                var filteredPaymentRecords = FundingSourceAndTransactionTypeFilter(paymentRecords).ToList();
                var rulebaseLearningDelivery = GetRulebaseLearningDelivery(appsCoInvestmentRulebaseInfo, learningDelivery);
                var completedPaymentRecordsInCurrentYear = paymentRecords.Where(p => p.AcademicYear == Generics.AcademicYear && p.TransactionType == 2).ToList();
                var totalsByPeriodDictionary = BuildCoinvestmentPaymentsPerPeriodDictionary(filteredPaymentRecords);
                var earliestPaymentInfo = GetEarliestPaymentInfo(paymentRecords);

                string legalEntityName = null;

                if (earliestPaymentInfo != null && earliestPaymentInfo.ApprenticeshipId.HasValue)
                {
                    apprenticeshipIdLegalEntityNameDictionary.TryGetValue(earliestPaymentInfo.ApprenticeshipId.Value, out legalEntityName);
                }

                var totalDueCurrentYear = totalsByPeriodDictionary.Sum(d => d.Value);
                var totalDuePreviousYear = filteredPaymentRecords.Where(p => p.AcademicYear < 1920).Sum(p => p.Amount);
                var totalCollectedCurrentYear = GetTotalPMRBetweenDates(learningDelivery, _academicYearStart, _nextAcademicYearStart);
                var totalCollectedPreviousYear = GetTotalPMRBetweenDates(learningDelivery, null, _academicYearStart);

                var model = new AppsCoInvestmentContributionsModel
                {
                    Ukprn = ukprn,
                    LearnRefNumber = record.LearnerReferenceNumber,
                    UniqueLearnerNumber = GetUniqueOrEmpty(paymentRecords, p => p.LearnerUln),
                    LearningStartDate = record.LearningStartDate,
                    ProgType = record.LearningAimProgrammeType,
                    StandardCode = record.LearningAimStandardCode,
                    FrameworkCode = record.LearningAimFrameworkCode,
                    ApprenticeshipPathway = record.LearningAimPathwayCode,
                    SoftwareSupplierAimIdentifier = learningDelivery?.SWSupAimId,
                    LearningDeliveryFAMTypeApprenticeshipContractType = GetUniqueOrEmpty(paymentRecords, p => p.ContractType),
                    EmployerIdentifierAtStartOfLearning = learner?.LearnerEmploymentStatus.Where(w => w.DateEmpStatApp <= record.LearningStartDate).OrderByDescending(o => o.DateEmpStatApp).FirstOrDefault()?.EmpId,
                    EmployerNameFromApprenticeshipService = legalEntityName,
                    EmployerCoInvestmentPercentage = GetEmployerCoInvestmentPercentage(filteredPaymentRecords),
                    ApplicableProgrammeStartDate = rulebaseLearningDelivery?.AppAdjLearnStartDate,
                    TotalPMRPreviousFundingYears = totalCollectedPreviousYear,
                    TotalCoInvestmentDueFromEmployerInPreviousFundingYears = totalDuePreviousYear,
                    TotalPMRThisFundingYear = totalCollectedCurrentYear,
                    TotalCoInvestmentDueFromEmployerThisFundingYear = totalDueCurrentYear,
                    PercentageOfCoInvestmentCollected = GetPercentageOfInvestmentCollected(totalDueCurrentYear, totalDuePreviousYear, totalCollectedCurrentYear, totalCollectedPreviousYear),
                    LDM356Or361 = HasLdm356Or361(learningDelivery) ? "Yes" : "No",
                    CompletionEarningThisFundingYear = CalculateCompletionEarningsThisFundingYear(learningDelivery, appsCoInvestmentRulebaseInfo),
                    CompletionPaymentsThisFundingYear = completedPaymentRecordsInCurrentYear.Sum(r => r.Amount),
                    CoInvestmentDueFromEmployerForAugust = GetPeriodisedValueFromDictionaryForPeriod(totalsByPeriodDictionary, 1),
                    CoInvestmentDueFromEmployerForSeptember = GetPeriodisedValueFromDictionaryForPeriod(totalsByPeriodDictionary, 2),
                    CoInvestmentDueFromEmployerForOctober = GetPeriodisedValueFromDictionaryForPeriod(totalsByPeriodDictionary, 3),
                    CoInvestmentDueFromEmployerForNovember = GetPeriodisedValueFromDictionaryForPeriod(totalsByPeriodDictionary, 4),
                    CoInvestmentDueFromEmployerForDecember = GetPeriodisedValueFromDictionaryForPeriod(totalsByPeriodDictionary, 5),
                    CoInvestmentDueFromEmployerForJanuary = GetPeriodisedValueFromDictionaryForPeriod(totalsByPeriodDictionary, 6),
                    CoInvestmentDueFromEmployerForFebruary = GetPeriodisedValueFromDictionaryForPeriod(totalsByPeriodDictionary, 7),
                    CoInvestmentDueFromEmployerForMarch = GetPeriodisedValueFromDictionaryForPeriod(totalsByPeriodDictionary, 8),
                    CoInvestmentDueFromEmployerForApril = GetPeriodisedValueFromDictionaryForPeriod(totalsByPeriodDictionary, 9),
                    CoInvestmentDueFromEmployerForMay = GetPeriodisedValueFromDictionaryForPeriod(totalsByPeriodDictionary, 10),
                    CoInvestmentDueFromEmployerForJune = GetPeriodisedValueFromDictionaryForPeriod(totalsByPeriodDictionary, 11),
                    CoInvestmentDueFromEmployerForJuly = GetPeriodisedValueFromDictionaryForPeriod(totalsByPeriodDictionary, 12),
                    CoInvestmentDueFromEmployerForR13 = GetPeriodisedValueFromDictionaryForPeriod(totalsByPeriodDictionary, 13),
                    CoInvestmentDueFromEmployerForR14 = GetPeriodisedValueFromDictionaryForPeriod(totalsByPeriodDictionary, 14)
                };

                return model;
            })
                   .Where(row => !IsExcludedRow(row))
                   .OrderBy(l => l.LearnRefNumber)
                   .ThenBy(t => t.LearningDeliveryFAMTypeApprenticeshipContractType));
        }
Exemple #8
0
 public IDictionary <string, LearnerInfo> BuildLearnerDictionary(AppsCoInvestmentILRInfo ilrInfo)
 {
     return(ilrInfo
            .Learners
            .ToDictionary(k => k.LearnRefNumber, v => v, StringComparer.OrdinalIgnoreCase));
 }