public CostStageRevisionTotalPayments Build(List <CostStageRevisionPaymentTotal> payments)
        {
            var totalPayments = new CostStageRevisionTotalPayments();

            if (payments != null)
            {
                totalPayments.InsuranceCostPayments         = payments.Where(x => x.LineItemTotalType == Constants.CostSection.InsuranceTotal).Select(x => x.LineItemTotalCalculatedValue).DefaultIfEmpty(0).Sum();
                totalPayments.TechnicalFeeCostPayments      = payments.Where(x => x.LineItemTotalType == Constants.CostSection.TechnicalFee).Select(x => x.LineItemTotalCalculatedValue).DefaultIfEmpty(0).Sum();
                totalPayments.TalentFeeCostPayments         = payments.Where(x => x.LineItemTotalType == Constants.CostSection.TalentFees).Select(x => x.LineItemTotalCalculatedValue).DefaultIfEmpty(0).Sum();
                totalPayments.PostProductionCostPayments    = payments.Where(x => x.LineItemTotalType == Constants.CostSection.PostProduction).Select(x => x.LineItemTotalCalculatedValue).DefaultIfEmpty(0).Sum();
                totalPayments.ProductionCostPayments        = payments.Where(x => x.LineItemTotalType == Constants.CostSection.Production).Select(x => x.LineItemTotalCalculatedValue).DefaultIfEmpty(0).Sum();
                totalPayments.TargetBudgetTotalCostPayments = payments.Where(x => x.LineItemTotalType == Constants.CostSection.TargetBudgetTotal).Select(x => x.LineItemTotalCalculatedValue).DefaultIfEmpty(0).Sum();
                totalPayments.OtherCostPayments             = payments.Where(x => x.LineItemTotalType == Constants.CostSection.Other).Select(x => x.LineItemTotalCalculatedValue).DefaultIfEmpty(0).Sum();

                var costTotalPayments = payments.Where(x => x.LineItemTotalType == Constants.CostSection.CostTotal);
                totalPayments.TotalCostPayments = costTotalPayments.Select(x => x.LineItemTotalCalculatedValue).DefaultIfEmpty(0).Sum();

                // it is only relevant for the last revision
                totalPayments.CarryOverAmount = costTotalPayments.OrderByDescending(x => x.CalculatedAt).Select(x => x.LineItemRemainingCost).DefaultIfEmpty(0).First();
            }
            else
            {
                totalPayments.ProductionCostPayments        = 0;
                totalPayments.InsuranceCostPayments         = 0;
                totalPayments.TechnicalFeeCostPayments      = 0;
                totalPayments.TalentFeeCostPayments         = 0;
                totalPayments.PostProductionCostPayments    = 0;
                totalPayments.OtherCostPayments             = 0;
                totalPayments.TargetBudgetTotalCostPayments = 0;
                totalPayments.TotalCostPayments             = 0;
            }

            return(totalPayments);
        }
        private List <PaymentAmountResult> GetNextStagesPaymentAmounts(
            PaymentAmountResult fResult,
            PgPaymentRule paymentRule,
            IEnumerable <StageModel> nextStages)
        {
            var isAipeProjection = paymentRule.IsAIPE && fResult.StageName == CostStages.Aipe.ToString();
            var result           = new List <PaymentAmountResult>();

            var currentResult = fResult;
            var currentInput  = paymentRule;

            foreach (var nextStage in nextStages)
            {
                var input = new PgPaymentRule
                {
                    // we only need these values for next stage projection calculation
                    CostStages = nextStage.Key,
                    // paymentRule already has current total - old payments. We only need to subtract
                    // the freshly calculated values for this stage
                    InsuranceCost         = currentInput.InsuranceCost - currentResult.InsuranceCostPayment,
                    OtherCost             = currentInput.OtherCost - currentResult.OtherCostPayment,
                    PostProductionCost    = currentInput.PostProductionCost - currentResult.PostProductionCostPayment,
                    ProductionCost        = currentInput.ProductionCost - currentResult.ProductionCostPayment,
                    TargetBudgetTotalCost = currentInput.TargetBudgetTotalCost - currentResult.TargetBudgetTotalPayment,
                    TechnicalFeeCost      = currentInput.TechnicalFeeCost - currentResult.TechnicalFeeCostPayment,
                    TalentFeeCost         = currentInput.TalentFeeCost - currentResult.TalentFeeCostPayment,
                    IsAIPE = currentInput.IsAIPE,
                    CostCarryOverAmount = currentResult.CostCarryOverAmount,

                    TotalCost       = currentInput.TotalCost - currentResult.TotalCostAmountPayment,
                    TotalCostAmount = currentResult.TotalCostAmount ?? 0m
                };
                var previousPayment = new CostStageRevisionTotalPayments
                {
                    InsuranceCostPayments         = currentResult.InsuranceCostPayment ?? 0,
                    TalentFeeCostPayments         = currentResult.TalentFeeCostPayment ?? 0,
                    TechnicalFeeCostPayments      = currentResult.TechnicalFeeCostPayment ?? 0,
                    PostProductionCostPayments    = currentResult.PostProductionCostPayment ?? 0,
                    ProductionCostPayments        = currentResult.ProductionCostPayment ?? 0,
                    OtherCostPayments             = currentResult.OtherCostPayment ?? 0,
                    CarryOverAmount               = currentResult.CostCarryOverAmount ?? 0,
                    TargetBudgetTotalCostPayments = currentResult.TargetBudgetTotalPayment ?? 0,
                    TotalCostPayments             = currentResult.TotalCostAmountPayment ?? 0
                };
                currentResult = CalculateStagePaymentAmountsWithRule(fResult.MatchedPaymentRule, nextStage.Key, input, true, previousPayment, isAipeProjection, isNextStageCalc: true);
                currentInput  = input;

                result.Add(currentResult);
            }

            return(result);
        }
        private PaymentAmountResult CalculateStagePaymentAmountsWithRule(
            dataAccess.Entity.Rule paymentRule,
            string costStageKey,
            PgPaymentRule input,
            bool isProjection,
            CostStageRevisionTotalPayments previousPayments,
            bool isAipeProjection       = false,
            CostSectionTotals rawTotals = null,
            bool isNextStageCalc        = false
            )
        {
            var res = new PaymentAmountResult();
            var pgPaymentRuleData = JsonConvert.DeserializeObject <PgPaymentRuleDefinition>(paymentRule.Definition);

            res.IsDetailedSplit = pgPaymentRuleData.DetailedSplit;
            var     costStage = (CostStages)Enum.Parse(typeof(CostStages), costStageKey);
            decimal?totalCalculatedValue;

            res.CostCarryOverAmount = 0;
            // do the specific calculations here:
            // - sum up all the individual costs
            // -- if it is an AIPE projection (projection of any stage triggered in AIPE stage) - we only have TargetBudgetTotal, so use that anyways
            if (pgPaymentRuleData.DetailedSplit && !isAipeProjection)
            {
                // ADC-2243: run through the payment allocation rule to ensure the 'input' is correctly allocated
                //ADC-2711: check null and get 0
                res.InsuranceCostPayment = GetAllocatedSplitPayment(input, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.InsuranceTotal, costStage) ?? 0;
                var talentFeeCostPayment = GetAllocatedSplitPayment(input, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.TalentFees, costStage);

                if (talentFeeCostPayment.HasValue)
                {
                    res.TalentFeeCostPayment = talentFeeCostPayment;
                }

                res.PostProductionCostPayment = GetAllocatedSplitPayment(input, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.PostProduction, costStage) ?? 0;
                res.ProductionCostPayment     = GetAllocatedSplitPayment(input, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.Production, costStage) ?? 0;
                res.TechnicalFeeCostPayment   = GetAllocatedSplitPayment(input, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.TechnicalFee, costStage) ?? 0;
                res.OtherCostPayment          = GetAllocatedSplitPayment(input, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.Other, costStage) ?? 0;

                res.TargetBudgetTotalPayment = 0m;

                // AIPE specific handling of target budget
                if (costStage == CostStages.Aipe)
                {
                    res.TargetBudgetTotalPayment = input.TargetBudgetTotalCost * (pgPaymentRuleData.GetSplitByNameAndStage(Constants.CostSection.TargetBudgetTotal, costStage) ?? 0);
                }

                totalCalculatedValue =
                    res.InsuranceCostPayment
                    + res.OtherCostPayment
                    + res.PostProductionCostPayment
                    + res.ProductionCostPayment
                    + res.TargetBudgetTotalPayment
                    + res.TechnicalFeeCostPayment;

                //ADC-2711: if DPV then exclude postproduction cost due to it has already included into Othercost in GetAllocation method
                if (paymentRule.Type == RuleType.VendorPayment)
                {
                    totalCalculatedValue = totalCalculatedValue - res.PostProductionCostPayment;
                }

                // we only need carry over amounts for detailed splits - for non detailed splits all payments are already contained within TotalCost
                if (costStage == CostStages.Aipe)
                {
                    // we store it as a carry over for other stages to deduct from
                    // only if the calculated value is > 0 - otherwise no payment is made in this stage -> no carry over amount
                    res.CostCarryOverAmount = totalCalculatedValue > 0 ? input.TotalCostAmount - totalCalculatedValue : 0;
                }
                else if (input.IsAIPE)
                {
                    if (input.CostCarryOverAmount > 0)
                    {
                        if (input.CostCarryOverAmount - totalCalculatedValue > 0)
                        {
                            // deduct current payment from the "pot" and store the remainder
                            res.CostCarryOverAmount = input.CostCarryOverAmount - totalCalculatedValue;
                        }
                        else
                        {
                            res.CostCarryOverAmount = 0;
                        }
                    }

                    // we need to subtract current payment from previous target budget total payments to never lose them
                    totalCalculatedValue = totalCalculatedValue - input.CostCarryOverAmount;
                }
                else
                {
                    if (totalCalculatedValue < 0)
                    {
                        // carry over amount will be negative in non-aipe overpayment cases
                        res.CostCarryOverAmount = totalCalculatedValue;
                    }
                }
            }
            else if (isAipeProjection && costStage == CostStages.FinalActual)
            {
                // we pretend to pay the rest on AIPE FA stage since detailed rules won't have a split for Cost Total
                totalCalculatedValue = input.TotalCost;
            }
            else
            {
                totalCalculatedValue = input.TotalCost * (pgPaymentRuleData.GetSplitByNameAndStage(Constants.CostSection.CostTotal, costStage) ?? 0);
            }

            // - if the stage = Final Actual - return whatever result (even if negative)
            // -  otherwise - if <=0 return 0
            if (totalCalculatedValue < 0 && costStage != CostStages.FinalActual && costStage != CostStages.FinalActualRevision)
            {
                res.TotalCostAmountPayment = 0;
            }
            else
            {
                if ((costStage == CostStages.FinalActual || costStage == CostStages.FinalActualRevision) && input.CostCarryOverAmount < 0)
                {
                    // previous stage resulted in a negative calculation, despite us reporting 0, we still need to subtract that negative value
                    totalCalculatedValue += input.CostCarryOverAmount;
                }

                res.TotalCostAmountPayment = totalCalculatedValue;
            }

            res.TotalCostAmount = totalCalculatedValue;

            res.MatchedPaymentRule = paymentRule;
            res.IsProjection       = isProjection;
            res.StageName          = input.CostStages;

            CostSectionTotals totals = null;

            if (rawTotals != null)
            {
                //ADC-2711 overwrite line_item_full_cost values to display on payment summary screen
                if (paymentRule.Type == RuleType.VendorPayment && isNextStageCalc == false)
                {
                    var insuranceCostPaymentAllocation      = GetAllocation(input, paymentRule.Type, Constants.CostSection.InsuranceTotal) ?? 0;
                    var postProductionCostPaymentAllocation = GetAllocation(input, paymentRule.Type, Constants.CostSection.PostProduction) ?? 0;
                    var productionCostPaymentAllocation     = GetAllocation(input, paymentRule.Type, Constants.CostSection.Production) ?? 0;
                    var technicalFeeCostPaymentAllocation   = GetAllocation(input, paymentRule.Type, Constants.CostSection.TechnicalFee) ?? 0;
                    var otherCostPaymentAllocation          = GetAllocation(input, paymentRule.Type, Constants.CostSection.Other) ?? 0;
                    var talentFeePaymentAllocation          = GetAllocation(input, paymentRule.Type, Constants.CostSection.TalentFees) ?? 0;


                    var insuranceCostTotal      = GetAllocatedAmount(rawTotals, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.InsuranceTotal, costStage) ?? 0;
                    var postProductionCostTotal = GetAllocatedAmount(rawTotals, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.PostProduction, costStage) ?? 0;
                    var productionCostTotal     = GetAllocatedAmount(rawTotals, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.Production, costStage) ?? 0;
                    var technicalFeeCostTotal   = GetAllocatedAmount(rawTotals, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.TechnicalFee, costStage) ?? 0;
                    var otherCostTotal          = GetAllocatedAmount(rawTotals, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.Other, costStage) ?? 0;
                    var talentFeeCostTotal      = GetAllocatedAmount(rawTotals, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.TalentFees, costStage) ?? 0;

                    totals = new CostSectionTotals
                    {
                        // Recalculate allocated amount because it depends on the rule
                        InsuranceCostTotal      = GetDisplayedValueOnPaymentSummaryPage(insuranceCostPaymentAllocation, insuranceCostTotal),
                        PostProductionCostTotal = GetDisplayedValueOnPaymentSummaryPage(postProductionCostPaymentAllocation, postProductionCostTotal),
                        ProductionCostTotal     = GetDisplayedValueOnPaymentSummaryPage(productionCostPaymentAllocation, productionCostTotal),
                        TechnicalFeeCostTotal   = GetDisplayedValueOnPaymentSummaryPage(technicalFeeCostPaymentAllocation, technicalFeeCostTotal),
                        OtherCostTotal          = GetDisplayedValueOnPaymentSummaryPage(otherCostPaymentAllocation - postProductionCostPaymentAllocation, otherCostTotal - postProductionCostTotal),
                        TalentFeeCostTotal      = GetDisplayedValueOnPaymentSummaryPage(talentFeePaymentAllocation, talentFeeCostTotal),
                        TargetBudgetTotal       = input.TargetBudgetTotalCost ?? 0 + previousPayments.TargetBudgetTotalCostPayments,
                        TotalCostAmountTotal    = input.TotalCostAmount
                    };
                }
                else
                {
                    totals = new CostSectionTotals
                    {
                        // Recalculate allocated amount because it depends on the rule
                        InsuranceCostTotal      = GetAllocatedAmount(rawTotals, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.InsuranceTotal, costStage) ?? 0,
                        PostProductionCostTotal = GetAllocatedAmount(rawTotals, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.PostProduction, costStage) ?? 0,
                        ProductionCostTotal     = GetAllocatedAmount(rawTotals, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.Production, costStage) ?? 0,
                        TechnicalFeeCostTotal   = GetAllocatedAmount(rawTotals, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.TechnicalFee, costStage) ?? 0,
                        OtherCostTotal          = GetAllocatedAmount(rawTotals, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.Other, costStage) ?? 0,
                        TalentFeeCostTotal      = GetAllocatedAmount(rawTotals, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.TalentFees, costStage) ?? 0,

                        TargetBudgetTotal    = input.TargetBudgetTotalCost ?? 0 + previousPayments.TargetBudgetTotalCostPayments,
                        TotalCostAmountTotal = input.TotalCostAmount
                    };
                }
            }

            var paymentTotals = new CostSectionTotals
            {
                // Recalculate allocated amount because it depends on the rule
                TalentFeeCostTotal      = GetAllocatedAmount(input, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.TalentFees, costStage) ?? 0,
                InsuranceCostTotal      = GetAllocatedAmount(input, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.InsuranceTotal, costStage) ?? 0,
                PostProductionCostTotal = GetAllocatedAmount(input, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.PostProduction, costStage) ?? 0,
                ProductionCostTotal     = GetAllocatedAmount(input, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.Production, costStage) ?? 0,
                TechnicalFeeCostTotal   = GetAllocatedAmount(input, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.TechnicalFee, costStage) ?? 0,
                OtherCostTotal          = GetAllocatedAmount(input, paymentRule.Type, pgPaymentRuleData, Constants.CostSection.Other, costStage) ?? 0,

                TargetBudgetTotal    = input.TargetBudgetTotalCost ?? 0 + previousPayments.TargetBudgetTotalCostPayments,
                TotalCostAmountTotal = input.TotalCostAmount
            };

            res.TotalRemainingPayment = new PgPaymentRule
            {
                BudgetRegion          = input.BudgetRegion,
                ContentType           = input.ContentType,
                CostType              = input.CostType,
                CostStages            = input.CostStages,
                ProductionType        = input.ProductionType,
                DirectPaymentVendorId = input.DirectPaymentVendorId,
                IsAIPE                = input.IsAIPE,
                TotalCostAmount       = input.TotalCostAmount,
                TotalCost             = input.TotalCost,
                TargetBudgetTotalCost = input.TargetBudgetTotalCost,
                CostCarryOverAmount   = input.CostCarryOverAmount,

                // Recalculate remaining payment amount because allocated amount depends on macthed rule
                StageTotals        = totals,
                InsuranceCost      = paymentTotals.InsuranceCostTotal - previousPayments.InsuranceCostPayments,
                TalentFeeCost      = paymentTotals.TalentFeeCostTotal - previousPayments.TalentFeeCostPayments,
                PostProductionCost = paymentTotals.PostProductionCostTotal - previousPayments.PostProductionCostPayments,
                ProductionCost     = paymentTotals.ProductionCostTotal - previousPayments.ProductionCostPayments,
                TechnicalFeeCost   = paymentTotals.TechnicalFeeCostTotal - previousPayments.TechnicalFeeCostPayments,
                OtherCost          = paymentTotals.OtherCostTotal - previousPayments.OtherCostPayments
            };

            return(res);
        }
        private async Task <PaymentAmountResult> GetPaymentAmount(PgPaymentRule paymentRule, CostStageRevisionTotalPayments previousPayments, CostSectionTotals totals, string productionCategory = null)
        {
            var rules = new List <CompiledRule <PgPaymentRule> >();

            // Try match the rules one by one. First Vendor specific rules, then AIPE/Non-AIPE rules, and then standart rules if nothing matched.
            if (paymentRule.DirectPaymentVendorId.HasValue)
            {
                var vendorRules = await _ruleService.GetCompiledByVendorId <PgPaymentRule>(paymentRule.DirectPaymentVendorId.Value, RuleType.VendorPayment, productionCategory);

                rules.AddRange(vendorRules);
            }

            if (paymentRule.IsAIPE)
            {
                var aipeRules = await _ruleService.GetCompiledByRuleType <PgPaymentRule>(RuleType.AIPEPayment);

                rules.AddRange(aipeRules);
            }
            else
            {
                var nonAipeRules = await _ruleService.GetCompiledByRuleType <PgPaymentRule>(RuleType.NonAIPEPayment);

                rules.AddRange(nonAipeRules);
            }

            var commonRules = await _ruleService.GetCompiledByRuleType <PgPaymentRule>(RuleType.CommonPayment);

            rules.AddRange(commonRules);

            PaymentAmountResult MatchFunc(PgPaymentRule t, dataAccess.Entity.Rule r) =>
            CalculateStagePaymentAmountsWithRule(r, paymentRule.CostStages, t, false, previousPayments, false, totals);

            _ruleService.TryMatchRule(rules, paymentRule, MatchFunc, out var fResult);

            return(fResult);
        }