/// <summary>
        /// This method generates the folio by concatenating the values Claim Reference, Claim Detail Reference and Claim Transaction Header Reference of a task.
        /// </summary>
        /// <param name="claimTransactionHeader">Claim Transaction Header</param>
        /// <returns>Returns folio</returns>
        public string GenerateFolio(ClaimTransactionHeader claimTransactionHeader)
        {
            ArgumentCheck.ArgumentNullCheck(claimTransactionHeader, "claimTransactionHeader");
            string folio = string.Empty;
            ClaimHeader clmHeader = claimTransactionHeader.ClaimHeader;
            string claimTransactionHeaderReference = claimTransactionHeader.ClaimTransactionHeaderReference;
            string claimReference = clmHeader.ClaimReference;

            if (claimTransactionHeader.ClaimTransactionGroups.Count == 1)
            {
                string claimDetailReference = claimTransactionHeader.ClaimTransactionGroups.Single().ClaimDetail.ClaimDetailReference;
                folio = string.Format("{0}-{1} {2}", claimReference, claimDetailReference, claimTransactionHeaderReference);
            }
            else
            {
                folio = string.Format("{0} {1}", claimReference, claimTransactionHeaderReference);
            }

           ClaimNameInvolvement claimNameInvolvement = ClaimsBusinessLogicHelper.GetInsuredFromHeader(clmHeader);
           folio = this.GenerateFolio(folio, claimNameInvolvement);
           if (_Logger.IsDebugEnabled)
           {
               _Logger.Debug(string.Format("Generated Folio is :", folio));
           }

           return folio;
        }
        public IEnumerable<ClaimFinancialAmount> ReadTransactionAmountData(ClaimTransactionHeader claimTransactionHeader, StaticValues.AmountType amountType)
        {
            ArgumentCheck.ArgumentNullCheck(claimTransactionHeader, "claimTransactionHeader");
            ArgumentCheck.ArgumentNullCheck(amountType, "amountType");

            if (_Logger.IsDebugEnabled)
            {
                _Logger.Debug(string.Format("ReadTransactionAmountData({0}, {1})", claimTransactionHeader.ClaimTransactionHeaderID, amountType));
            }
            var flattenedTransactions = claimTransactionHeader.ClaimHeader
                .GetFlattenedTransactionData()
                .Where(t => t.ClaimTransactionHeaderID == claimTransactionHeader.ClaimTransactionHeaderID);

            var transactions = from t in flattenedTransactions
                               where t.AmountType == (short)amountType && t.TransactionAmountOriginal != null
                               select CreateClaimFinancialAmount(t);

            return transactions.ToList();
        }
        public void Initialize()
        {
            var container = new UnityContainer();
            ObjectFactory.Instance = new ObjectFactory(container);

            this.currentUser = new User { UserIdentity = "currentUserIdentity", UserID = 1 };
            this.supervisor = new User { UserIdentity = "manager", UserID = 2 };
            this.currentUser.ManagerID = this.supervisor.UserID;

            this.header = new ClaimTransactionHeader { CustomReference01 = RefereeIdentity };

            var claimsEntities = MockRepository.GenerateStub<IClaimsQuery>();
            claimsEntities.Stub(a => a.GetClaimTransactionHeader(TransactionHeaderID)).IgnoreArguments().Return(this.header);
            container.RegisterInstance<IClaimsQuery>(claimsEntities);

            var metadataEntities = MockRepository.GenerateStub<IMetadataQuery>();
            metadataEntities.Stub(a => a.GetUserByUserIdentity(this.currentUser.UserIdentity)).Return(this.currentUser);
            metadataEntities.Stub(a => a.GetUserByUserId(this.supervisor.UserID)).Return(this.supervisor);
            container.RegisterInstance(metadataEntities);
        }
        public IEnumerable<ClaimFinancialAmount> ReadTransactionAmountData(ClaimTransactionHeader claimTransactionHeader, bool includeEstimated, StaticValues.AmountType amountType)
        {
            ArgumentCheck.ArgumentNullCheck(claimTransactionHeader, "claimTransactionHeader");
            ArgumentCheck.ArgumentNullCheck(amountType, "amountType");

            if (_Logger.IsDebugEnabled)
            {
                _Logger.Debug(string.Format("ReadTransactionAmountData({0}, {1}, {2})", claimTransactionHeader.ClaimTransactionHeaderID, includeEstimated, amountType));
            }

            var flattenedTransactions = claimTransactionHeader.ClaimHeader
                .GetFlattenedTransactionData()
                .Where(t => t.ClaimTransactionHeaderID == claimTransactionHeader.ClaimTransactionHeaderID);

            var amounts = flattenedTransactions.Where(t => t.AmountType == (short)amountType);
            if (!includeEstimated) amounts = amounts.Where(t => t.ReserveType != (short)StaticValues.ReserveType.Estimated);
            amounts = amounts.Where(t => t.TransactionAmountOriginal != null);
                          
            return amounts.Select(CreateClaimFinancialAmount);
        }
        public bool Calculate(ClaimTransactionHeader claimTransactionHeader)
        {
            var transactionGroupCount = claimTransactionHeader.ClaimTransactionGroups.Count;

            if (transactionGroupCount == 0)
            {
                _Logger.Warn(string.Format("There are no transaction groups for this transaction header\r\n{0}",
                    JObject.FromObject(new{claimTransactionHeader.ClaimHeader.ClaimReference, claimTransactionHeader.ClaimTransactionHeaderReference})));
                return false;
            }

            if (transactionGroupCount > 1)
            {
                _Logger.Warn(string.Format("There is more than one transaction group for this transaction header\r\n{0}",
                    JObject.FromObject(new{claimTransactionHeader.ClaimHeader.ClaimReference, claimTransactionHeader.ClaimTransactionHeaderReference})));
                return false;
            }

            var claimHeader = claimTransactionHeader.ClaimHeader;
            var claimTransactionGroup = claimTransactionHeader.ClaimTransactionGroups.Single();
            var claimDetail = claimTransactionGroup.ClaimDetail;
            var user = claimHeader.Context.GetUser(Xiap.Framework.Security.XiapSecurity.GetUser().UserID);
            var financialContext = new CalculateDeductiblesHandler.FinancialTransactionContext(claimHeader, claimDetail, claimTransactionHeader, claimTransactionGroup, user);
            var result = GenerateDeductibles(financialContext);
            if (!result.Success)
            {
                return false;
            }

            ResetAmoundChangedFlag(claimTransactionHeader);

            if (_Logger.IsDebugEnabled)
            {
                PrintFinancialTransaction(claimTransactionHeader);
            }

            return true;
        }
        /// <summary>
        /// Load historical reserves/payments/recovery reserves/recovery receipts for the specified claim
        /// </summary>
        /// <param name="transactionSource">transaction source</param>
        /// <param name="productClaimDefinition">claim product</param>
        /// <param name="claimDetailProductMap">claim details used for filtering</param>
        /// <param name="claimHeader">claim header</param>
        /// <param name="reserves">resulting reserves</param>
        /// <param name="payments">resulting payments and recovery receipts</param>
        /// <param name="recoveryReserves">resulting recovery reserves</param>
        private static void LoadFinancialAmounts(StaticValues.ClaimTransactionSource transactionSource, ProductClaimDefinition productClaimDefinition, IDictionary<string, ProductClaimDetail> claimDetailProductMap, ClaimHeader claimHeader, ClaimTransactionHeader claimtransactionheader, out IEnumerable<ClaimFinancialAmount> reserves, out IEnumerable<ClaimFinancialAmount> payments, out IEnumerable<ClaimFinancialAmount> recoveryReserves)
        {
            var inProgressData = ObjectFactory.Resolve<IInProgressFinancialAmountData>();
            var historicalData = ObjectFactory.Resolve<IHistoricalFinancialAmountData>();

            var claimHeaderArg = new ClaimHeaderArgument(AmountDataSource.Both, claimHeader, claimtransactionheader);

            var validClaimDetails = claimDetailProductMap
                .Where(a => a.Value.ClaimDetailAutomaticDeductibleProcessingMethod == (short)StaticValues.ClaimDetailAutomaticDeductibleProcessingMethod.FromClaimHeader)
                .Select(a => a.Key);

            var reserveCalculation = new TotalClaimReserveFinancialCalculation(inProgressData, historicalData);
            var paymentCalcuation = new TotalClaimPaymentFinancialCalculation(inProgressData, historicalData);
            var recoveryReceiptCalculation = new TotalClaimReceiptFinancialCalculation(inProgressData, historicalData);
            var recoveryRerserveCalculation = new TotalClaimRecoveryReserveFinancialCalculation(inProgressData, historicalData);
            bool includeEstimated = productClaimDefinition.IncurredAmountDerivationMethod == (short)StaticValues.IncurredAmountDerivationMethod.PaymentsReservesincludingEstimated;
            bool includeRecoveryEstimated = productClaimDefinition.RecoveryIncurredAmountDerivationMethod == (short)StaticValues.RecoveryIncurredAmountDerivationMethod.ReceiptsRecoveryReservesincludingEstimated;
            reserves = reserveCalculation.ReadLatestClaimReserves(claimHeaderArg, includeEstimated).Where(a => validClaimDetails.Contains(a.ClaimDetailReference));
            payments = paymentCalcuation.ReadClaimPayments(claimHeaderArg).Where(a => validClaimDetails.Contains(a.ClaimDetailReference));
            payments = payments.Concat(recoveryReceiptCalculation.ReadClaimReceipts(claimHeaderArg).Where(a => validClaimDetails.Contains(a.ClaimDetailReference)));
            recoveryReserves = recoveryRerserveCalculation.ReadLatestClaimRecoveryReserves(claimHeaderArg, includeRecoveryEstimated).Where(a => validClaimDetails.Contains(a.ClaimDetailReference));


            var excludedMovementTypes = ClaimsBusinessLogicHelper.GetExcludedMovementTypesFromAutomaticDeductibleCalculations();
            reserves = FilterExcludedMovementTypes(reserves, excludedMovementTypes);
            recoveryReserves = FilterExcludedMovementTypes(recoveryReserves, excludedMovementTypes);
            payments = FilterExcludedMovementTypes(payments, excludedMovementTypes);

            reserves = CreateAmountsForCalculation(reserves);
            recoveryReserves = CreateAmountsForCalculation(recoveryReserves);
            payments = CreateAmountsForCalculation(payments);
        }
        private static ClaimTransactionGroup ResolveClaimTransactionGroup(ClaimTransactionHeader claimTransactionHeader, ClaimTransactionGroup currentClaimTransactionGroup, ClaimDetail claimDetail)
        {
            var claimTransactionGroup = claimTransactionHeader.ClaimTransactionGroups.SingleOrDefault(a => a.ClaimDetail == claimDetail);
            if (claimTransactionGroup == null)
            {
                claimTransactionGroup = claimTransactionHeader.AddNewClaimTransactionGroup(claimDetail, false);
                claimTransactionGroup.UpdateData(currentClaimTransactionGroup);
                // don't want to copy the id accross
                claimTransactionGroup.ClaimTransactionGroupID = 0;
            }

            return claimTransactionGroup;
        }
        /// <summary>
        /// Is this an authorised amount on the ClaimTransactionHeader
        /// </summary>
        /// <param name="isRootComponentClaimHeader">Root Component Header</param>
        /// <param name="claimTransactionHeader">Processing Claim Transaction Header</param>
        /// <returns>return true if Authorize otherwise false</returns>
        private bool IsAmountAuthorized(bool? isRootComponentClaimHeader, ClaimTransactionHeader claimTransactionHeader)
        {
            // Return false for claim transaction headers that are in progress.
            if (isRootComponentClaimHeader.HasValue && isRootComponentClaimHeader.Value && !claimTransactionHeader.IsInProgress)
            {
                return false;
            }

            // Do we already have a transfer item for this Claim Transaction Header? If so, return false to stop us creating a new one.
            if (Xiap.Framework.Common.ClaimTransfer.IsClaimTransferControlLogExists(claimTransactionHeader.ClaimTransactionHeaderID))
            {
                return false;
            }

            short? transactionSource = claimTransactionHeader.ClaimTransactionSource;

            if ((transactionSource == (short)StaticValues.ClaimTransactionSource.Payment && claimTransactionHeader.PaymentAuthorisationStatus == (short)StaticValues.PaymentAuthorisationStatus.PaymentAuthorised)
                || (transactionSource == (short)StaticValues.ClaimTransactionSource.Reserve && claimTransactionHeader.ReserveAuthorisationStatus == (short)StaticValues.ReserveAuthorisationStatus.ReserveAuthorised)
                || (transactionSource == (short)StaticValues.ClaimTransactionSource.RecoveryReserve && claimTransactionHeader.RecoveryReserveAuthorisationStatus == (short)StaticValues.RecoveryReserveAuthorisationStatus.RecoveryReserveAuthorised)
                || (transactionSource == (short)StaticValues.ClaimTransactionSource.RecoveryReceipt && claimTransactionHeader.RecoveryReceiptAuthorisationStatus == (short)StaticValues.RecoveryReceiptAuthorisationStatus.RecoveryReceiptAuthorised)
                || (transactionSource == (short)StaticValues.ClaimTransactionSource.PaymentCancellation && claimTransactionHeader.PaymentAuthorisationStatus == (short)StaticValues.PaymentAuthorisationStatus.PaymentAuthorised))
            {
                // if this is an authorised item.
                return true;
            }

            return false;
        }
 public IEnumerable<ClaimFinancialAmount> ReadUsersClaimPaymentAmountData(ClaimHeader claimHeader, SecurityUser userID, StaticValues.AuthorisationResult authorisationResult, FinancialAmountParticipationFilter filter, ClaimTransactionHeader claimTransactionHeader, bool isExcludedFromCurrent = false)
 {
     throw new System.NotImplementedException();
 }
        private static void PrintFinancialTransaction(ClaimTransactionHeader header)
        {
            var claimTransactionGroup = header.ClaimTransactionGroups.Single();
            _Logger.Debug("Deductibles Calculation Results Begin");
            foreach (var claimTransactionDetail in claimTransactionGroup.ClaimTransactionDetails)
            {
                _Logger.Debug(string.Format("        ClaimTransactionDetail[ MovementType = {0}, Original Amount = {1}, Claim Amount {2}]",
                    claimTransactionDetail.MovementType,
                    claimTransactionDetail.TransactionAmountOriginal,
                    claimTransactionDetail.TransactionAmountClaimCurrency));
            }

            _Logger.Debug("Deductibles Calculation Results End");
        }
        private static void ProcessTransaction(
            ClaimHeader claimHeader,
            ClaimTransactionHeader claimTransactionHeader, 
            CalculateDeductiblesHandler calculateDeductiblesHandler)
        {
            try
            {
                claimTransactionHeader.Context = claimHeader.Context;
                claimTransactionHeader.SetToInProgress();
                //axaCalculateDeductiblePlugin.ProcessComponent(claimTransactionHeader, ProcessInvocationPoint.Virtual, 0);
                calculateDeductiblesHandler.Calculate(claimTransactionHeader);
                claimTransactionHeader.SetToNotInProgress();

                GlobalClaimWakeUp.ClearAttachedData(claimHeader.ClaimReference);
                Logger.InfoFormat("Executed Deductible calculation for\r\n{0}\r\n", JObject.FromObject(new { claimHeader.ClaimReference, claimTransactionHeader.ClaimTransactionHeaderReference }));
            }
            catch (Exception ex)
            {

                Logger.ErrorFormat("Exception thrown while executing E&D\r\n{0}\r\n",
                    JObject.FromObject(new { claimHeader.ClaimReference, claimTransactionHeader.ClaimTransactionHeaderReference, ex.Message, ex.StackTrace }));
            }

        }
 /// <summary>
 /// Create Event of type Cancel Payment against the Claim Detail
 /// </summary>
 /// <param name="clmDetail">Claim Detail</param>
 /// <param name="clmTransHeader">Claim Transaction Header</param>
 /// <param name="productEventID">Product EventID</param>
 private void CreateEvent(ClaimDetail clmDetail, ClaimTransactionHeader clmTransHeader, long productEventID)
 {
     if (clmDetail != null)
     {
       ClaimEvent claimEvent = clmDetail.AddNewClaimEvent(productEventID, true);
       // If we are using CustomText01 on the Claim Event
       // UI Label = Cancellation Reason; Payment Cancelled Task
       if (clmTransHeader != null && claimEvent.CustomText01Field.IsInUse == true)
       {
           // Put the cancellation reason in ot CustomText01
           // CustomText01 = Cancellation Reason
            claimEvent.CustomText01 = clmTransHeader.ClaimTransactionDescription;   // UI Label = Cancellation Reason; Payment Cancelled Task
       }
     }
 }
        /// <summary>
        /// Load historical reserves/payments/recovery reserves/recovery receipts for the specified claim detail
        /// </summary>
        /// <param name="transactionSource">transaction source</param>
        /// <param name="productClaimDefinition">claim product</param>
        /// <param name="claimDetail">claim detail</param>
        /// <param name="reserves">resulting reserves</param>
        /// <param name="payments">resulting payments and recovery receipts</param>
        /// <param name="recoveryReserves">resulting recovery reserves</param>
        private static void LoadFinancialAmounts(StaticValues.ClaimTransactionSource transactionSource, ProductClaimDefinition productClaimDefinition, ClaimDetail claimDetail, ClaimTransactionHeader claimtransactionheader, out IEnumerable<ClaimFinancialAmount> reserves, out IEnumerable<ClaimFinancialAmount> payments, out IEnumerable<ClaimFinancialAmount> recoveryReserves)
        {
            var inProgressData = ObjectFactory.Resolve<IInProgressFinancialAmountData>();
            var historicalData = ObjectFactory.Resolve<IHistoricalFinancialAmountData>();

            var claimDetailArg = new ClaimDetailArgument(AmountDataSource.Both, claimDetail, null);

            var reserveCalculation = new TotalClaimDetailReserveFinancialCalculation(inProgressData, historicalData);
            var paymentCalcuation = new TotalClaimDetailPaymentFinancialCalculation(inProgressData, historicalData);
            var recoveryReceiptCalculation = new TotalClaimDetailReceiptFinancialCalculation(inProgressData, historicalData);
            var recoveryRerserveCalculation = new TotalClaimDetailRecoveryReserveFinancialCalculation(inProgressData, historicalData);
            bool includeEstimated = productClaimDefinition.RecoveryIncurredAmountDerivationMethod == (short)StaticValues.RecoveryIncurredAmountDerivationMethod.ReceiptsRecoveryReservesincludingEstimated;
            bool includeRecoveryEstimated = productClaimDefinition.RecoveryIncurredAmountDerivationMethod == (short)StaticValues.RecoveryIncurredAmountDerivationMethod.ReceiptsRecoveryReservesincludingEstimated;
            reserves = reserveCalculation.ReadLatestClaimDetailReserves(claimDetailArg, includeEstimated);
            payments = paymentCalcuation.ReadClaimDetailPayments(claimDetailArg);
            payments = payments.Concat(recoveryReceiptCalculation.ReadClaimDetailReceipt(claimDetailArg));
            recoveryReserves = recoveryRerserveCalculation.ReadLatestClaimDetailRecoveryReserves(claimDetailArg, includeRecoveryEstimated);

            var excludedMovementTypes = ClaimsBusinessLogicHelper.GetExcludedMovementTypesFromAutomaticDeductibleCalculations();
            reserves = FilterExcludedMovementTypes(reserves, excludedMovementTypes);
            recoveryReserves = FilterExcludedMovementTypes(recoveryReserves, excludedMovementTypes);
            payments = FilterExcludedMovementTypes(payments, excludedMovementTypes);

            reserves = CreateAmountsForCalculation(reserves);
            recoveryReserves = CreateAmountsForCalculation(recoveryReserves);
            payments = CreateAmountsForCalculation(payments);
        }
        /// <summary>
        /// Check user grade Structure Type based on claim type. 
        /// If there are no claim details on the claim, return an empty string.
        /// </summary>
        /// <param name="claimtransactionheader">Claim transaction header</param>
        /// <returns>Grade Structure Type</returns>
        private string GetGradeStructureType(ClaimTransactionHeader claimtransactionheader)
        {
            string gradeStructureType= string.Empty;
            ClaimHeader clmHeader = claimtransactionheader.ClaimHeader;
            if (clmHeader.ClaimDetails != null)
            {
                switch (clmHeader.ClaimHeaderAnalysisCode01.ToUpper())
                {
                    case ClaimConstants.CH_ANALYSISCODE_LIABILITY:
                        gradeStructureType = ClaimConstants.PRODUCT_LIABILITY_GRADESTRUCTURETYPE;
                        break;
                    case ClaimConstants.CH_ANALYSISCODE_MOTOR:
                        if (clmHeader.ClaimDetails.Any(d => d.ClaimDetailTypeCode == ClaimConstants.CLAIMDETAILTYPECODE_TPI))
                        {
                            gradeStructureType = ClaimConstants.PRODUCT_MOTOR_GRADESTRUCTURETYPE_CLAIMDETAIL_TPI;
                        }
                        else
                        {
                            gradeStructureType = ClaimConstants.PRODUCT_MOTOR_GRADESTRUCTURETYPE_CLAIMDETAIL_NOTTPI;
                        }

                        break;
                }
            }

            return gradeStructureType;
        }
 /// <summary>
 /// Check if the user can Manually Authorise the payment 
 /// </summary>
 /// <param name="user">Syatem User</param>
 /// <param name="checkLog"> Collection of ClaimFinancialAuthorityLimitCheckResult </param>
 /// <param name="product"> Product Version </param>
 /// <param name="check"> Claim Financial Authority Check Type </param>
 /// <param name="header"> Claim mHeader</param>
 /// <param name="claimTransactionHeader"> Claim Transaction Header </param>
 /// <returns> True / False</returns>
 protected bool CanPerformManualCheck(User user, List<ClaimFinancialAuthorityLimitCheckResult> checkLog, ProductVersion product, StaticValues.ClaimFinancialAuthorityCheckType check, ClaimHeader header, ClaimTransactionHeader claimTransactionHeader)
 {
     FinancialAuthorityCheckComponents components = new FinancialAuthorityCheckComponents(claimTransactionHeader.ClaimHeader, null, claimTransactionHeader);
     var claimArgs = new ClaimHeaderArgument(AmountDataSource.Historical, header, claimTransactionHeader);
     var result = ClaimFinancialAuthorityCheckUtil.PerformUserLimitCheck(user.UserID, product, StaticValues.ClaimFinancialAuthorityLimitType.LimitForManualAuthorisation, check, claimArgs, components,null);
     checkLog.Add(result);
     return result == ClaimFinancialAuthorityLimitCheckResult.NullValue || result.IsAuthorised;
 }
        /// <summary>
        /// Check if the user can Manually Authorise the payment 
        /// </summary>
        /// <param name="user"> System User </param>
        /// <param name="checkLog"> Collection of Claim Financial Authority Limit Check Result </param>
        /// <param name="product"> Product Version  </param>
        /// <param name="check"> Enum Claim Financial Authority Check Type</param>
        /// <param name="claimTransactionHeader">Claim Transaction Header</param>
        /// <returns> Bool True / False </returns>
        protected bool CanPerformManualCheck(User user, List<ClaimFinancialAuthorityLimitCheckResult> checkLog, ProductVersion product, StaticValues.ClaimFinancialAuthorityCheckType check, ClaimTransactionHeader claimTransactionHeader)
        {
            FinancialAuthorityCheckComponents components = new FinancialAuthorityCheckComponents(claimTransactionHeader.ClaimHeader, null, claimTransactionHeader);

            var claimTransactionArgs = new ClaimTransactionHeaderArgument(AmountDataSource.Historical, claimTransactionHeader);
            // Determine if the manual auth is possible.
            var result = ClaimFinancialAuthorityCheckUtil.PerformUserLimitCheck(user.UserID, product, StaticValues.ClaimFinancialAuthorityLimitType.LimitForManualAuthorisation, check, claimTransactionArgs, components, null);
            // Add the result to the checklog that was passed in, a list of results of the ClaimFinancialAuthorityChecks
            checkLog.Add(result);
            // Return true or false, appropriately
            return result == ClaimFinancialAuthorityLimitCheckResult.NullValue || result.IsAuthorised;
        }
        /// <summary>
        /// Check if the user can Authorise this payment or not
        /// </summary>
        /// <param name="user"> System User </param>
        /// <param name="claimTransactionHeader"> Claim Transaction Header </param>
        /// <returns> True / False </returns>
        private bool CanUserAuthorisePayment(User user, ClaimTransactionHeader claimTransactionHeader)
        {
            // Can only authorise unauthorised items. Return false if it's not in that list.
            if (claimTransactionHeader.PaymentAuthorisationStatus == (short)StaticValues.PaymentAuthorisationStatus.PaymentAuthorised
                || claimTransactionHeader.PaymentAuthorisationStatus == (short)StaticValues.PaymentAuthorisationStatus.PaymentRejected
                || claimTransactionHeader.PaymentAuthorisationStatus == (short)StaticValues.PaymentAuthorisationStatus.NotApplicable)
            {
                if (_Logger.IsDebugEnabled)
                {
                    _Logger.Debug(string.Format("CanUserAuthorisePayment({0}, {1}) => invalid claim transaction header status", user.UserIdentity, claimTransactionHeader.ClaimTransactionHeaderID));
                }
                
                return false;
            }

            // Don't authorise a reserve if it's not pending a payment
            if (claimTransactionHeader.ReserveAuthorisationStatus == (short)StaticValues.ReserveAuthorisationStatus.ReserveUnauthorised
                && claimTransactionHeader.IsReservePendingPaymentAction == false)
            {
                if (_Logger.IsDebugEnabled)
                {
                    _Logger.Debug(string.Format("CanUserAuthorisePayment({0}, {1}) => invalid reserve status", user.UserIdentity, claimTransactionHeader.ClaimTransactionHeaderID));
                }
                
                return false;
            }

            var claimHeader = claimTransactionHeader.ClaimHeader;
            var product = claimHeader.GetProduct();
            var checkLog = new List<ClaimFinancialAuthorityLimitCheckResult>();

            // Check if the current user can do a manual authorisation based on the Transaction Payment Amount
            if (!this.CanPerformManualCheck(user, checkLog, product, CheckType.TransactionPaymentAmount, claimTransactionHeader))
            {
                if (_Logger.IsDebugEnabled)
                {
                    _Logger.Debug(string.Format("CanUserAuthorisePayment({0}, {1}) => No: TransactionPaymentAmount", user.UserIdentity, claimTransactionHeader.ClaimTransactionHeaderID));
                }
                
                return false;
            }

            // Check if total on the Claim Details prevents the user from manually authorising this amount.
            foreach (var claimTransactionGroup in claimTransactionHeader.ClaimTransactionGroups)
            {
                var claimDetail = claimTransactionGroup.ClaimDetail;
                if (!this.CanPerformManualCheck(user, checkLog, product, CheckType.TotalClaimDetailPaymentAmount, claimDetail, claimTransactionHeader))
                {
                    if (_Logger.IsDebugEnabled)
                    {
                        _Logger.Debug(string.Format("CanUserAuthorisePayment({0}, {1}) => No: TotalClaimDetailPaymentAmount", user.UserIdentity, claimTransactionHeader.ClaimTransactionHeaderID));
                    }
                    
                    return false;
                }
            }

            // Check if the total claim payment amount prevents the user from authorising this claim payment
            if (!this.CanPerformManualCheck(user, checkLog, product, CheckType.TotalClaimPaymentAmount, claimHeader, claimTransactionHeader))
            {
                if (_Logger.IsDebugEnabled)
                {
                    _Logger.Debug(string.Format("CanUserAuthorisePayment({0}, {1}) => No: TotalClaimPaymentAmount", user.UserIdentity, claimTransactionHeader.ClaimTransactionHeaderID));
                }
                
                return false;
            }

            // Check if the total incurred amount on the Claim Detail prevents the user from manually authorising the payment
            foreach (var claimTransactionGroup in claimTransactionHeader.ClaimTransactionGroups)
            {
                var claimDetail = claimTransactionGroup.ClaimDetail;
                if (!this.CanPerformManualCheck(user, checkLog, product, CheckType.TotalClaimDetailIncurredAmount, claimDetail, claimTransactionHeader))
                {
                    if (_Logger.IsDebugEnabled)
                    {
                        _Logger.Debug(string.Format("CanUserAuthorisePayment({0}, {1}) => No: TotalClaimDetailIncurredAmount", user.UserIdentity, claimTransactionHeader.ClaimTransactionHeaderID));
                    }
                    
                    return false;
                }
            }

            // Check if the total incurred amount on the claim prevents a manual authorisation of the payment by the user
            if (!this.CanPerformManualCheck(user, checkLog, product, CheckType.TotalClaimIncurredAmount, claimHeader, claimTransactionHeader))
            {
                if (_Logger.IsDebugEnabled)
                {
                    _Logger.Debug(string.Format("CanUserAuthorisePayment({0}, {1}) => No: TotalClaimIncurredAmount", user.UserIdentity, claimTransactionHeader.ClaimTransactionHeaderID));
                }
                
                return false;
            }

            // If any authorisation check wasn't active, rather than returning true or false
            // AND we don't allow manual authorisation without these checks, return false.
            if (checkLog.Count(a => a != ClaimFinancialAuthorityLimitCheckResult.NullValue) == 0
                && !product.ProductClaimDefinition.IsManualAuthorisationAlwaysAllowedIfNoChecksAreActive.GetValueOrDefault(false))
            {
                if (_Logger.IsDebugEnabled)
                {
                    _Logger.Debug(string.Format("CanUserAuthorisePayment({0}, {1}) => No checks configured", user.UserIdentity, claimTransactionHeader.ClaimTransactionHeaderID));
                }
                
                return false;
            }

            // Allowed to authorise
            return true;
        }
        /////// <summary>
        /////// Create Event on claimDetail
        /////// </summary>
        /////// <param name="clmDetail">Claim Detail</param>
        /////// <param name="clmTransHeader">Claim Transaction Header</param>
        /////// <param name="product">Product Version</param>
        /////// <param name="eventTypeCode">event Type Code</param>
        
        private void CreateEvent(ClaimHeader clmHeader,ClaimDetail clmDetail, ClaimTransactionHeader clmTransHeader, ProductVersion product, string eventTypeCode)
        {
            // find an event on the Product for this claim that matches the required event type
            bool EventExists= false;
            var productEvent = ProductService.GetProductEventQuery().GetProductEvents(clmTransHeader.ClaimHeader.ProductVersionID.GetValueOrDefault())
                       .Where(x => x.EventTypeCode == eventTypeCode).FirstOrDefault();
            if (eventTypeCode == ClaimConstants.EVENT_TYPECODE_RECOVERYRECEIPT)
            {
                EventExists = this.ChkIfEventExists(clmHeader, productEvent);
            }

            if (productEvent != null && !EventExists)
            {
                ClaimEvent claimEvent = null;
                // Get a list of all claim details on all Claim Transaction Groups on this ClaimTransactionHeader
                IEnumerable<ClaimDetail> claimDetails = clmTransHeader.ClaimTransactionGroups.Select(a => a.ClaimDetail).Distinct();
                if (claimDetails.Count() == 1)
                {
                    // We only have one claim detail so add the event to that claim detail
                        ClaimDetail claimDetail = claimDetails.First();
                        claimEvent = claimDetail.AddNewClaimEvent(productEvent.ProductEventID, true);
                }
                else
                {
                    // We have multiple claim details, so add the event at the Claim Transaction Header level
                    claimEvent = clmTransHeader.ClaimHeader.AddNewClaimEvent(productEvent.ProductEventID, true);
                }

                if (claimEvent.CustomText01Field.IsInUse == true)
                {
                    // Set the cancellation reason, CustomText01
                    claimEvent.CustomText01 = clmTransHeader.ClaimTransactionDescription;
                }
            }
        }
        private static void ResetAmoundChangedFlag(ClaimTransactionHeader header)
        {
            var claimTransactionDetails = from ctg in header.ClaimTransactionGroups
                                          from ctd in ctg.ClaimTransactionDetails
                                          select ctd;

            foreach (var claimTransactionDetail in claimTransactionDetails)
            {
                claimTransactionDetail.HasSourceAmountOriginalChanged = false;
            }
        }
 public IEnumerable<ClaimFinancialAmount> ReadTransactionAmountData(ClaimTransactionHeader claimTransactionHeader, bool includeEstimated, StaticValues.AmountType amountType, FinancialAmountParticipationFilter filter, bool? isIndemnityMovementExcluded, bool? isFeeMovementExcluded, bool? isRecoveryMovementExcluded, bool isExcludedFromCurrent = false)
 {
     throw new System.NotImplementedException();
 }
            public FinancialTransactionContext(ClaimHeader claimHeader, ClaimDetail claimDetail, ClaimTransactionHeader claimTransactionHeader, ClaimTransactionGroup claimTransactionGroup, User user)
            {
                this.ClaimHeader = claimHeader;
                this.ClaimDetail = claimDetail;
                this.ClaimTransactionHeader = claimTransactionHeader;
                this.ClaimTransactionGroup = claimTransactionGroup;
                this.CurrentUser = user;
                this.TransactionSource = (StaticValues.ClaimTransactionSource)this.ClaimTransactionHeader.ClaimTransactionSource;

                this.Product = claimHeader.GetProduct();
                this.ProductClaimDefinition = this.Product.ProductClaimDefinition;
                this.ProductClaimDetails = this.Product.ClaimDetails;
            }
 public IEnumerable<ClaimFinancialAmount> ReadTransactionAmountData(ClaimTransactionHeader claimTransactionHeader, StaticValues.AmountType amountType, FinancialAmountParticipationFilter filter, bool isExcludedFromCurrent = false)
 {
     throw new System.NotImplementedException();
 }