public decimal GetRenewalDelayedDaysAmount(BO.HomeInsurancePolicyDetails policy, BO.HomeProduct homeProduct, decimal netPremium)
        {
            decimal delayedDaysAmount = 0;

            if (policy.HomeInsurancePolicy.RenewalDelayedDays > 0)
            {
                delayedDaysAmount = (netPremium * policy.HomeInsurancePolicy.RenewalDelayedDays) / 365;
            }
            return(delayedDaysAmount);
        }
        private void Calculate(BO.HomeInsurancePolicyDetails policy, BO.HomeProduct homeProduct)
        {
            //Calcuate the base premium.
            BuildingPremium = homeProduct.Rate * policy.HomeInsurancePolicy.BuildingValue / 100;
            ContentPremium  = homeProduct.Rate * policy.HomeInsurancePolicy.ContentValue / 100;
            //Premium = BuildingPremium + ContentPremium;
            BaseBuildingContentRate = homeProduct.Rate;

            //Calculate the riot premium.
            if (policy.HomeInsurancePolicy.IsRiotStrikeDamage.ToString().ToLower() == "y")
            {
                BuildingRiot  = homeProduct.RiotCoverRate * policy.HomeInsurancePolicy.BuildingValue / 100;
                ContentRiot   = homeProduct.RiotCoverRate * policy.HomeInsurancePolicy.ContentValue / 100;
                JewelleryRiot = homeProduct.RiotCoverRate * policy.HomeInsurancePolicy.JewelleryValue / 100;

                TotalRiot = BuildingRiot + ContentRiot;

                if (TotalRiot <= homeProduct.RiotCoverMinAmount)
                {
                    TotalRiot = homeProduct.RiotCoverMinAmount;
                }
                RiotRate = homeProduct.RiotCoverRate;
            }

            //Calculate the home domestic helper amount.
            if (policy.HomeInsurancePolicy.NoOfDomesticWorker > 0 || policy.HomeDomesticHelpdt.Rows.Count > 0)
            {
                var domesticHelpers = policy.HomeDomesticHelpdt.Rows.Count;
                DomesticHelperAmount = domesticHelpers > 0 ? (domesticHelpers - 1) * homeProduct.DomesticHelperAmount : 0;
            }

            //Calculate the jewellery amount.
            var jCover = homeProduct.JewelleryCover.Find(x => x.KeyType == policy.HomeInsurancePolicy.JewelleryCover);

            if (jCover != null)
            {
                JewellerAmount = jCover.Amount;
                if (jCover.KeyType == "EXTREME")
                {
                    JewellerAmount = jCover.Rate * policy.HomeInsurancePolicy.JewelleryValue / 100;
                }
            }

            // TotalPremium = Math.Round(Premium + TotalRiot + DomesticHelperAmount + JewellerAmount, 3, MidpointRounding.AwayFromZero);
            TotalBasicPremium = Math.Round(BuildingPremium + ContentPremium, 3, MidpointRounding.AwayFromZero);
            TotalSRCCPremium  = Math.Round(BuildingRiot + ContentRiot + JewelleryRiot, 3, MidpointRounding.AwayFromZero);

            if (TotalBasicPremium <= homeProduct.MinimumPremium)
            {
                TotalBasicPremium = homeProduct.MinimumPremium;
            }

            TotalBasicPremium = TotalBasicPremium + DomesticHelperAmount + JewellerAmount;

            TotalPremium = TotalBasicPremium + TotalSRCCPremium;

            //Deduct the renewal delayed days amount from the premium.
            if (policy.HomeInsurancePolicy.RenewalDelayedDays > 0)
            {
                var renewalDelayedAmount = GetRenewalDelayedDaysAmount(policy, homeProduct, BuildingPremium + ContentPremium + TotalRiot + DomesticHelperAmount + JewellerAmount);
                TotalPremium = Math.Round(BuildingPremium + ContentPremium + TotalRiot + DomesticHelperAmount + JewellerAmount - renewalDelayedAmount, 3, MidpointRounding.AwayFromZero);

                var renewalDelayedAmount1 = GetRenewalDelayedDaysAmount(policy, homeProduct, BuildingPremium + ContentPremium + DomesticHelperAmount + JewellerAmount);
                TotalBasicPremium = Math.Round(BuildingPremium + ContentPremium + DomesticHelperAmount + JewellerAmount - renewalDelayedAmount1, 3, MidpointRounding.AwayFromZero);

                var renewalDelayedAmount2 = GetRenewalDelayedDaysAmount(policy, homeProduct, BuildingRiot + ContentRiot);
                TotalSRCCPremium = Math.Round(BuildingRiot + ContentRiot - renewalDelayedAmount2, 3, MidpointRounding.AwayFromZero);
            }

            PremiumBeforeDiscount = TotalPremium;

            //Calculate the commission.
            CommissionBeforeDiscount = GetCommision(policy.HomeInsurancePolicy, TotalBasicPremium, TotalSRCCPremium);

            //If the user give the discount
            if (!policy.HomeInsurancePolicy.UserChangedPremium)
            {
                PremiumAfterDiscount    = PremiumBeforeDiscount;
                CommissionAfterDiscount = CommissionBeforeDiscount;
            }
            else
            {
                PremiumAfterDiscount    = policy.HomeInsurancePolicy.PremiumAfterDiscount;
                CommissionAfterDiscount = policy.HomeInsurancePolicy.CommissionAfterDiscount;
            }

            //Calculate the VAT.
            TaxOnBasicPremium             = GetTax(TotalBasicPremium, homeProduct.TaxRate);
            TaxOnSRCCPremium              = GetTax(TotalSRCCPremium, homeProduct.TaxRate);
            TaxOnPremiumBeforeDiscount    = GetTax(PremiumBeforeDiscount, homeProduct.TaxRate);
            TaxOnPremiumAfterDiscount     = GetTax(PremiumAfterDiscount, homeProduct.TaxRate);
            TaxOnCommissionBeforeDiscount = GetTax(CommissionBeforeDiscount, homeProduct.TaxRate);
            TaxOnCommissionAfterDiscount  = GetTax(CommissionAfterDiscount, homeProduct.TaxRate);

            //Apply discount.
            Discount = PremiumBeforeDiscount - PremiumAfterDiscount;

            //Set HIR - building or content value exceeded the maximum value policy will move to HIR status admin need to approve.
            SetHIR(homeProduct, policy.HomeInsurancePolicy);
        }
        private BO.PolicyRecord InsertHomeMain(BO.HomeInsurancePolicyDetails policy, string spName)
        {
            SqlParameter[] paras = new SqlParameter[]
            {
                new SqlParameter("@HomeID", policy.HomeInsurancePolicy.HomeID),
                new SqlParameter("@InsuredCode", policy.HomeInsurancePolicy.InsuredCode),
                new SqlParameter("@InsuredName", policy.HomeInsurancePolicy.InsuredName),
                new SqlParameter("@CPR", policy.HomeInsurancePolicy.CPR),
                new SqlParameter("@Agency", policy.HomeInsurancePolicy.Agency),
                new SqlParameter("@AgentCode", policy.HomeInsurancePolicy.AgentCode),
                new SqlParameter("@BranchCode", policy.HomeInsurancePolicy.AgentBranch),
                new SqlParameter("@MainClass", policy.HomeInsurancePolicy.MainClass),
                new SqlParameter("@SubClass", policy.HomeInsurancePolicy.SubClass),
                new SqlParameter("@MobileNumber", !string.IsNullOrEmpty(policy.HomeInsurancePolicy.Mobile)
                                                                      ? policy.HomeInsurancePolicy.Mobile:""),

                new SqlParameter("@PolicyStartDate", policy.HomeInsurancePolicy.PolicyStartDate != null?
                                 policy.HomeInsurancePolicy.PolicyStartDate:(object)DBNull.Value),

                new SqlParameter("@BuildingValue", policy.HomeInsurancePolicy.BuildingValue),
                new SqlParameter("@ContentValue", policy.HomeInsurancePolicy.ContentValue),
                new SqlParameter("@JewelleryValue", policy.HomeInsurancePolicy.JewelleryValue),
                new SqlParameter("@BuildingAge", policy.HomeInsurancePolicy.BuildingAge),
                new SqlParameter("@IsPropertyMortgaged", policy.HomeInsurancePolicy.IsPropertyMortgaged),
                new SqlParameter("@FinancierCode", !string.IsNullOrEmpty(policy.HomeInsurancePolicy.FinancierCode)
                                                                       ? policy.HomeInsurancePolicy.FinancierCode : ""),

                new SqlParameter("@IsSafePropertyInsured", policy.HomeInsurancePolicy.IsSafePropertyInsured),
                new SqlParameter("@JewelleryCover", policy.HomeInsurancePolicy.JewelleryCover),
                new SqlParameter("@IsRiotStrikeDamage", policy.HomeInsurancePolicy.IsRiotStrikeDamage),
                new SqlParameter("@IsJointOwnership", policy.HomeInsurancePolicy.IsJointOwnership),

                new SqlParameter("@JointOwnerName", !string.IsNullOrEmpty(policy.HomeInsurancePolicy.JointOwnerName)
                                                                        ? policy.HomeInsurancePolicy.JointOwnerName :""),
                new SqlParameter("@NamePolicyReasonSeekingReasons", !string.IsNullOrEmpty(policy.HomeInsurancePolicy.NamePolicyReasonSeekingReasons)
                                                                                      ? policy.HomeInsurancePolicy.NamePolicyReasonSeekingReasons : ""),

                new SqlParameter("@IsPropertyInConnectionTrade", policy.HomeInsurancePolicy.IsPropertyInConnectionTrade),
                new SqlParameter("@IsPropertyCoveredOtherInsurance", policy.HomeInsurancePolicy.IsPropertyCoveredOtherInsurance),
                new SqlParameter("@IsPropertyInsuredSustainedAnyLoss", policy.HomeInsurancePolicy.IsPropertyInsuredSustainedAnyLoss),
                new SqlParameter("@IsPropertyUndergoingConstruction", policy.HomeInsurancePolicy.IsPropertyUndergoingConstruction),
                new SqlParameter("@IsSingleItemAboveContents", policy.HomeInsurancePolicy.IsSingleItemAboveContents),

                new SqlParameter("@BuildingNo", !string.IsNullOrEmpty(policy.HomeInsurancePolicy.BuildingNo)?
                                 policy.HomeInsurancePolicy.BuildingNo:""),

                new SqlParameter("@FlatNo", !string.IsNullOrEmpty(policy.HomeInsurancePolicy.FlatNo) ?  policy.HomeInsurancePolicy.FlatNo:""),
                new SqlParameter("@HouseNo", !string.IsNullOrEmpty(policy.HomeInsurancePolicy.HouseNo) ? policy.HomeInsurancePolicy.HouseNo:""),
                new SqlParameter("@NoOfFloors", policy.HomeInsurancePolicy.NoOfFloors),
                new SqlParameter("@Area", !string.IsNullOrEmpty(policy.HomeInsurancePolicy.Area) ? policy.HomeInsurancePolicy.Area:""),
                new SqlParameter("@BuildingType", policy.HomeInsurancePolicy.BuildingType),
                new SqlParameter("@RoadNo", !string.IsNullOrEmpty(policy.HomeInsurancePolicy.RoadNo) ? policy.HomeInsurancePolicy.RoadNo:""),
                new SqlParameter("@BlockNo", !string.IsNullOrEmpty(policy.HomeInsurancePolicy.BlockNo) ? policy.HomeInsurancePolicy.BlockNo:""),
                new SqlParameter("@ResidanceTypeCode", policy.HomeInsurancePolicy.BuildingType == 1 ? "H" : "F"),
                new SqlParameter("@FFPNumber", !string.IsNullOrEmpty(policy.HomeInsurancePolicy.FFPNumber) ? policy.HomeInsurancePolicy.FFPNumber:""),
                new SqlParameter("@IsRequireDomestic", policy.HomeInsurancePolicy.IsRequireDomestic),
                new SqlParameter("@NumberOfDomesticWorker", policy.HomeInsurancePolicy.NoOfDomesticWorker),
                new SqlParameter("@CreatedBy", policy.HomeInsurancePolicy.CreatedBy),
                new SqlParameter("@AuthorizedBy", policy.HomeInsurancePolicy.AuthorizedBy),
                new SqlParameter("@IsSaved", policy.HomeInsurancePolicy.IsSaved),
                new SqlParameter("@IsActive", policy.HomeInsurancePolicy.IsActivePolicy),
                new SqlParameter("@PaymentType", string.IsNullOrEmpty(policy.HomeInsurancePolicy.PaymentType) ? string.Empty : policy.HomeInsurancePolicy.PaymentType),
                new SqlParameter("@AccountNumber", string.IsNullOrEmpty(policy.HomeInsurancePolicy.AccountNumber)? string.Empty : policy.HomeInsurancePolicy.AccountNumber),
                new SqlParameter("@Remarks", string.IsNullOrEmpty(policy.HomeInsurancePolicy.Remarks) ? string.Empty : policy.HomeInsurancePolicy.Remarks),
                new SqlParameter("@HomeSubItemsdt", policy.HomeSubItemsdt),
                new SqlParameter("@HomeDomesticdt", policy.HomeDomesticHelpdt),
                new SqlParameter("@PremiumBeforeDiscount", PremiumBeforeDiscount),
                new SqlParameter("@PremiumAfterDiscount", PremiumAfterDiscount),
                new SqlParameter("@CommissionBeforeDiscount", CommissionBeforeDiscount),
                new SqlParameter("@CommissionAfterDiscount", CommissionAfterDiscount),
                new SqlParameter("@TaxOnPremiumBeforeDiscount", TaxOnPremiumBeforeDiscount),
                new SqlParameter("@TaxOnPremiumAfterDiscount", TaxOnPremiumAfterDiscount),
                new SqlParameter("@TaxOnCommissionBeforeDiscount", TaxOnCommissionBeforeDiscount),
                new SqlParameter("@TaxOnCommissionAfterDiscount", TaxOnCommissionAfterDiscount),
                new SqlParameter("@BuildingPremium", BuildingPremium),
                new SqlParameter("@ContentPremium", ContentPremium),
                new SqlParameter("@TotalPremium", TotalPremium),
                new SqlParameter("@BuildingRiot", BuildingRiot),
                new SqlParameter("@ContentRiot", ContentRiot),
                new SqlParameter("@TotalRiot", TotalRiot),
                new SqlParameter("@JewelleryAmount", JewellerAmount),
                new SqlParameter("@DomesticHelperAmount", DomesticHelperAmount),
                new SqlParameter("@Discount", Discount),
                new SqlParameter("@RiotRate", RiotRate),
                new SqlParameter("@Rate", BaseBuildingContentRate),
                new SqlParameter("@IsHIR", IsHIR),
                new SqlParameter("@HIRReason", HIRReason ?? string.Empty),
                new SqlParameter("@HIRStatus", HIRStatus),
                new SqlParameter("@UserChangedPremium", policy.HomeInsurancePolicy.UserChangedPremium),
                new SqlParameter("@OldDocumentNumber", policy.HomeInsurancePolicy.OldDocumentNumber ?? string.Empty),
                new SqlParameter("@RenewalDocumentNumber", policy.HomeInsurancePolicy.DocumentNo ?? string.Empty),
                new SqlParameter("@OldRenewalCount", policy.HomeInsurancePolicy.RenewalCount),
                new SqlParameter("@RenewalDelayedDays", policy.HomeInsurancePolicy.RenewalDelayedDays),
                new SqlParameter("@ActualRenewalStartDate", policy.HomeInsurancePolicy.ActualRenewalStartDate.HasValue ? policy.HomeInsurancePolicy.ActualRenewalStartDate : (object)DBNull.Value)
            };
            List <SPOut> outParams = new List <SPOut>()
            {
                new SPOut()
                {
                    OutPutType = SqlDbType.Int, ParameterName = "@NewHomeID"
                },
                new SPOut()
                {
                    OutPutType = SqlDbType.NVarChar, ParameterName = "@DocumentNumber", Size = 100
                },
                new SPOut()
                {
                    OutPutType = SqlDbType.NVarChar, ParameterName = "@LinkIDNew", Size = 100
                },
                new SPOut()
                {
                    OutPutType = SqlDbType.Int, ParameterName = "@RenewalCount"
                },
            };

            object[] dataSet      = BKICSQL.GetValues(spName, paras, outParams);
            var      HomeID       = Convert.ToInt64(dataSet[0]);
            var      DocNo        = Convert.ToString(dataSet[1]);
            var      LinkID       = Convert.ToString(dataSet[2]);
            var      RenewalCount = Convert.ToInt32(dataSet[3]);

            return(new BO.PolicyRecord
            {
                IsInserted = true,
                DocumentNumber = DocNo,
                LinkID = LinkID,
                NewHomeID = HomeID,
                RenewalCount = RenewalCount
            });
        }
        public BKIC.SellingPoint.DL.BO.HomeInsurancePolicyResponse InsertHome(BO.HomeInsurancePolicyDetails policy)
        {
            try
            {
                var req = new BO.HomeProductRequest
                {
                    Type      = "fetch",
                    Agency    = policy.HomeInsurancePolicy.Agency,
                    AgentCode = policy.HomeInsurancePolicy.AgentCode,
                    MainClass = policy.HomeInsurancePolicy.MainClass,
                    SubClass  = policy.HomeInsurancePolicy.SubClass
                };
                BO.HomeProductResponse productRes = _adminRepository.GetHomeProduct(req);
                if (productRes != null && productRes.IsTransactionDone && productRes.HomeProducts.Count > 0)
                {
                    var homeProduct = productRes.HomeProducts[0];
                    if (homeProduct != null)
                    {
                        Calculate(policy, homeProduct);
                        var policyRecord = InsertHomeMain(policy, policy.HomeInsurancePolicy.IsRenewal ? HomeInsuranceSP.InsertHomeRenewal : HomeInsuranceSP.InsertHome);
                        if (policyRecord != null && policyRecord.IsInserted)
                        {
                            CalculateCommission(homeProduct, policy.HomeInsurancePolicy, policyRecord.NewHomeID,
                                                policyRecord.DocumentNumber, policyRecord.LinkID, policyRecord.RenewalCount);

                            if (policyRecord.NewHomeID > 0 && !IsHIR && policy.HomeInsurancePolicy.IsActivePolicy)
                            {
                                try
                                {
                                    new Task(() =>
                                    {
                                        SqlParameter[] para = new SqlParameter[]
                                        {
                                            new SqlParameter("@HomeID", policyRecord.NewHomeID)
                                        };
                                        SellingPointSQL.eds("MIG_IntegrateHomeDetails", para);
                                    }).Start();
                                }
                                catch (AggregateException ex)
                                {
                                    foreach (Exception inner in ex.InnerExceptions)
                                    {
                                        _mail.SendMailLogError(inner.Message, policy.HomeInsurancePolicy.InsuredCode,
                                                               "HomeInsurance", policy.HomeInsurancePolicy.Agency, true);
                                    }
                                }
                            }
                            return(new BO.HomeInsurancePolicyResponse()
                            {
                                IsTransactionDone = true,
                                HomeId = policyRecord.NewHomeID,
                                IsHIR = IsHIR,
                                DocumentNo = policyRecord.DocumentNumber,
                                RenewalCount = policyRecord.RenewalCount
                            });
                        }
                    }
                    return(new BKIC.SellingPoint.DL.BO.HomeInsurancePolicyResponse()
                    {
                        IsTransactionDone = false,
                        TransactionErrorMessage = "Product not found"
                    });
                }
                return(new BKIC.SellingPoint.DL.BO.HomeInsurancePolicyResponse()
                {
                    IsTransactionDone = false,
                    TransactionErrorMessage = "Product not found"
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }