Exemplo n.º 1
0
        private FinanceServiceArrangementRequest AddCollateralRequirements(FinanceServiceArrangementRequest request)
        {
            if (request.ProductSnapshot.AvailableCollateralModelsData.Count > 0)
            {
                ProductCollateralModel selectedModel = null;
                if (!String.IsNullOrEmpty(request.ProductSnapshot.DefaultCollateralModel))
                {
                    selectedModel = request.ProductSnapshot.AvailableCollateralModelsData.Find(c => c.Code == request.ProductSnapshot.DefaultCollateralModel);
                }
                if (selectedModel == null)
                {
                    selectedModel = request.ProductSnapshot.AvailableCollateralModelsData[0];
                }

                request.CollateralModel = selectedModel.Code;
                if (request.CollateralRequirements == null)
                {
                    request.CollateralRequirements = new List <CollateralRequirement>();
                }
                foreach (var requirement in selectedModel.CollateralRequirements)
                {
                    var collateralRequirement = new CollateralRequirement
                    {
                        // Application = request.Application,
                        ArrangementRequestId    = request.ArrangementRequestId,
                        CollateralRequirementId = (request.CollateralRequirements.Count > 0) ?
                                                  request.CollateralRequirements.Max(x => x.CollateralRequirementId) + 1 : 1,
                        CollateralArrangementCode = requirement.CollateralArrangementCode,
                        FromModel       = true,
                        MinimalCoverage = requirement.MinimalCoverage,
                        MinimalCoverageInLoanCurrency = request.Amount * (requirement.MinimalCoverage / 100),
                        ActualCoverage = 0
                    };
                    request.CollateralRequirements.Add(collateralRequirement);
                }
            }
            return(request);
        }
        public async Task <ArrangementRequest> Handle(InitiateCalculateOfferCommand message, CancellationToken cancellationToken)
        {
            ProductConditions conditions = await _priceCalculation.ReadVariationDefinitions(message.ProductConditions);

            var parameters = Mapper.Map <InitiateCalculateOfferCommand, ArrangementRequestInitializationParameters>(message);

            try
            {
                parameters.MaturityDate = Utility.GetEndDateFromPeriod(parameters.Term, message.CalculationDate);
            }
            catch (InvalidTermException)
            {
                // do nothing
            }
            ArrangementRequest result = _requestFactory.GetForArrangementKind(parameters, message.ArrangementKind);

            if (parameters.MaturityDate.HasValue && result.IsFinanceService())
            {
                FinanceServiceArrangementRequest fsr = result as FinanceServiceArrangementRequest;
                fsr.MaturityDate = parameters.MaturityDate.Value;
            }

            result.ParentProductCode = message.PartOfBundle;
            result.Campaign          = message.Campaign;
            result.Options           = message.ProductOptions;
            if (result is FinanceServiceArrangementRequest finRequest)
            {
                finRequest.CollateralModel = message.CollateralModel;
            }
            Dictionary <string, OptionGroup> productShapsotOptions = new Dictionary <string, OptionGroup>();

            if (message.ProductOptions != null)
            {
                foreach (var option in message.ProductOptions)
                {
                    if (productShapsotOptions.TryGetValue(option.GroupCode, out OptionGroup optionGroup))
                    {
                        optionGroup.Options.Add(new Option
                        {
                            Code        = option.Code,
                            Description = option.Description,
                            Effects     = option.Effects
                        });
                    }
                    else
                    {
                        productShapsotOptions.Add(option.GroupCode, new OptionGroup
                        {
                            Code        = option.GroupCode,
                            Description = option.GroupDescription,
                            Options     = new List <Option>
                            {
                                new Option
                                {
                                    Code        = option.Code,
                                    Description = option.Description,
                                    Effects     = option.Effects
                                }
                            }
                        });
                    }
                }
            }
            result.ProductSnapshot = new ProductSnapshot
            {
                Conditions   = conditions,
                Campaign     = message.Campaign,
                OptionGroups = productShapsotOptions.Values.ToList(),
                MinimumDaysForFirstInstallment = message.MinimumDaysForFirstInstallment
            };

            OfferApplication application = new OfferApplication
            {
                CustomerSegment = message.CustomerSegment,
                CollateralModel = message.CollateralModel,
                RiskScore       = message.RiskScore ?? null,
                ChannelCode     = message.Channel,
                DebtToIncome    = message.DebtToIncome,
                CustomerValue   = message.CustomerValue,
                CreditRating    = message.CreditRating,
                RequestDate     = message.RequestDate
            };

            try
            {
                _logger.LogInformation("Calculating offer for term: {term}, annuity: {annutiy} and amount {amount} and interest rate: {rate}", message.Term, message.Annuity, message.Amount, message.InterestRate);

                result = _calculatorProvider.Calculate(result, application, message.BundledComponents);
                RemoveDmnFields(result);

                try
                {
                    await _auditClient.WriteLogEntry(AuditLogEntryAction.Execute, AuditLogEntryStatus.Success, "application", application.ApplicationNumber, "Calculating offer for term: " + message.Term + ", annuity: " + message.Annuity + " and amount " + message.Amount, new { });
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Audit error in UpdateApplicationStatusCommandHandler");
                }

                return(result);
            }
            catch (MaxNumberOfIterationsException e)
            {
                _logger.LogInformation("Error in calculation: {calcErr}. Command data: {command}", e.Message, message);
                throw e;
            }
            catch (Exception exp)
            {
                _logger.LogError(exp, "Exception while calculating offer for data, term: {term}, annuity: {annutiy} and amount {amount} and interest rate: {rate}", message.Term, message.Annuity, message.Amount, message.InterestRate);
                throw new NotImplementedException(exp.Message);
            }
        }
Exemplo n.º 3
0
        public async Task <ArrangementRequest> BootstrapArrangementRequest(ArrangementRequestInitializationParameters parameters,
                                                                           ProductSnapshot productData, OfferApplication application)
        {
            #region Create initial
            ArrangementKind?arrangementKind = OfferUtility.GetArrangmentKindByProductKind(productData.Kind);
            parameters = GetInitializationParametersFromProduct(productData, parameters) ?? new ArrangementRequestInitializationParameters();
            var arrangementRequest = GetForProductKind(parameters, productData);
            arrangementRequest.ArrangementRequestId = GetNextRequestIdForApplication(application);
            arrangementRequest.Application          = application;
            arrangementRequest.ProductSnapshot      = productData;
            arrangementRequest.ArrangementKind      = arrangementKind;
            arrangementRequest.ProductName          = arrangementRequest.ProductName ?? productData.Name;
            arrangementRequest.CalculationDate      = arrangementRequest.CalculationDate ?? DateTime.UtcNow;
            arrangementRequest.ProductCode          = parameters.ProductCode ?? productData.ProductCode;
            arrangementRequest.Conditions           = parameters.Conditions;
            arrangementRequest.Options          = parameters.ProductOptions;
            arrangementRequest.IsAbstractOrigin = parameters.IsAbstractOrigin ?? false;
            arrangementRequest.RepaymentType    = parameters.RepaymentType ?? null;
            arrangementRequest.InstallmentScheduleDayOfMonth = parameters.InstallmentScheduleDayOfMonth;
            #endregion
            arrangementRequest.ProductSnapshotDb = await _productSnapshotRepository.PostProductSnapshot(productData);

            if (arrangementRequest is FinanceServiceArrangementRequest ara)
            {
                #region Resolve for Finance service
                arrangementRequest = AddCollateralRequirements(ara);
                var conversionMethod = _configurationService.GetEffective("offer/fee-currency-conversion-method", "Buy to middle").Result;
                var domesticCurrency = _configurationService.GetEffective("domestic-currency", "RSD").Result;

                if (domesticCurrency != null)
                {
                    if (domesticCurrency == parameters.Currency)
                    {
                        ara.AmountInDomesticCurrency = parameters.Amount ?? 0;
                    }
                    else if (ara.Amount != 0)
                    {
                        var financial = (FinanceServiceArrangementRequest)arrangementRequest;
                        CurrencyConverter currencyConverter = new CurrencyConverter();
                        financial.AmountInDomesticCurrency = currencyConverter.CurrencyConvert(financial.Amount, financial.Currency,
                                                                                               domesticCurrency, DateTime.Today.ToString("o", CultureInfo.InvariantCulture), conversionMethod);
                    }
                }
                #endregion
            }


            if (arrangementRequest is OverdraftFacilityRequest)
            {
                #region Resolve accounts for overdraft
                var arrangementList = await _arrangementService.GetArrangements(parameters.CustomerNumber);

                var arr = arrangementList?.FirstOrDefault();
                if (arr != null)
                {
                    List <ArrangementAccountInfo> arrangementAccounts = new List <ArrangementAccountInfo>();
                    JArray accountList     = (JArray)arr["accounts"];
                    var    primaryAccounts = accountList.Where(x => x["role-kind"].ToString().Equals("primary-account")).ToList();
                    foreach (var account in primaryAccounts)
                    {
                        var accountNumber = account["account-number"].ToString();
                        ArrangementAccountInfo newAccount = new ArrangementAccountInfo
                        {
                            AccountNumber = accountNumber,
                            RoleKind      = ArrangementAccountRoleKind.SettlementAccount
                        };
                        arrangementAccounts.Add(newAccount);
                    }
                    arrangementRequest.Accounts = arrangementAccounts;
                }
                #endregion
            }

            if (!string.IsNullOrEmpty(parameters.CustomerNumber))
            {
                #region Resolve campaigns
                var leadList = await _campaignService.GetCampaigns(parameters.CustomerNumber);

                var productCampaign = leadList?.Leads?.Where(l => l.ProductCode == arrangementRequest.ProductCode).FirstOrDefault();
                arrangementRequest.ProductSnapshot.Campaign = productCampaign;
                arrangementRequest.Campaign = productCampaign;
                #endregion
            }

            if (!parameters.MaturityDate.HasValue && arrangementRequest.IsFinanceService() && parameters.Term != null)
            {
                FinanceServiceArrangementRequest fsr = arrangementRequest as FinanceServiceArrangementRequest;
                fsr.MaturityDate = Utility.GetEndDateFromPeriod(parameters.Term);
            }
            return(arrangementRequest);
        }