Esempio n. 1
0
        public async Task <bool?> Handle(DeleteArrangementRequestCommand message, CancellationToken cancellationToken)
        {
            ArrangementRequest arrangementRequest;

            arrangementRequest = _arrangementRequestRepository.GetArrangementRequest(message.ApplicationNumber,
                                                                                     message.ArrangementRequestId, "product-snapshot", null);
            if (arrangementRequest == null)
            {
                return(null);
            }
            var requestsToDelete = _arrangementRequestRepository.GetBundledRequests(arrangementRequest, false);

            requestsToDelete.Add(arrangementRequest);
            var result = await _arrangementRequestRepository.DeleteArrangementRequests(message.ApplicationNumber, requestsToDelete);

            var application = await _applicationRepository.GetAsync(message.ApplicationNumber);

            var messageObj = _messageEventFactory.CreateBuilder("offer", "product-selection-changed")
                             .AddHeaderProperty("application-number", application.ApplicationNumber);

            messageObj = messageObj.AddBodyProperty("product-code", application.ProductCode)
                         .AddBodyProperty("product-name", application.ProductName);
            _eventBus.Publish(messageObj.Build());

            await _auditClient.WriteLogEntry(AuditLogEntryAction.Delete, AuditLogEntryStatus.Success, "arrangement", message.ApplicationNumber.ToString(), "Arrangement deleted " + arrangementRequest.ArrangementRequestId, new { });

            return(result);
        }
        public async Task <bool?> Handle(UpdateCollateralModelCommand message, CancellationToken cancellationToken)
        {
            var arrangementRequest = _arrangementRequestRepository.GetArrangementRequest(message.ApplicationNumber, message.ArrangementRequestId, "collateral-requirements,product-snapshot", null);

            if (arrangementRequest == null)
            {
                return(null);
            }
            if (arrangementRequest is FinanceServiceArrangementRequest ara && ara.ProductSnapshot.AvailableCollateralModels.Contains(message.CollateralModel))
            {
                var selectedModel = ara.ProductSnapshot.AvailableCollateralModelsData.Where(m => m.Code.Equals(message.CollateralModel)).FirstOrDefault();
                if (selectedModel != null)
                {
                    ara.CollateralModel = message.CollateralModel;
                    if (ara.CollateralRequirements == null)
                    {
                        ara.CollateralRequirements = new List <CollateralRequirement>();
                    }
                    foreach (var newRequirement in selectedModel.CollateralRequirements)
                    {
                        var existingRequirement = ara.CollateralRequirements.Where(c => c.CollateralArrangementCode.Equals(newRequirement.CollateralArrangementCode)).Any();
                        if (!existingRequirement)
                        {
                            var req = new CollateralRequirement
                            {
                                ApplicationId                 = message.ApplicationNumber,
                                ArrangementRequestId          = message.ArrangementRequestId,
                                CollateralArrangementCode     = newRequirement.CollateralArrangementCode,
                                MinimalCoverage               = newRequirement.MinimalCoverage,
                                MinimalCoverageInLoanCurrency = ara.Amount * (newRequirement.MinimalCoverage / 100),
                                ActualCoverage                = 0,
                                CollateralRequirementId       = (ara.CollateralRequirements.Count > 0) ? ara.CollateralRequirements.Max(x => x.CollateralRequirementId) + 1 : 1,
                                FromModel = true
                            };
                            ara.CollateralRequirements.Add(req);
                        }
                    }
                    List <CollateralRequirement> deletionList = new List <CollateralRequirement>();
                    foreach (var requirement in ara.CollateralRequirements)
                    {
                        var query = selectedModel.CollateralRequirements.Where(x => x.CollateralArrangementCode.Equals(requirement.CollateralArrangementCode));
                        requirement.FromModel = query.Any();
                        if (!requirement.FromModel && requirement.SecuredDealLinks == null) // not from model and empty
                        {
                            deletionList.Add(requirement);
                        }
                    }
                    foreach (var requirement in deletionList)
                    {
                        ara.CollateralRequirements.Remove(requirement);
                    }
                }
                else
                {
                    return(false);
                }
            }
        public IActionResult GetCollateralRequrements([FromRoute] long applicationNumber, [FromRoute] int arrangementRequestId)
        {
            var arrRequest = _arrangementRequestRepository.GetArrangementRequest(applicationNumber, arrangementRequestId, "collateral-requirements", null);

            if (arrRequest == null || !(arrRequest is FinanceServiceArrangementRequest))
            {
                return(NotFound());
            }
            return(Ok(new { ((FinanceServiceArrangementRequest)arrRequest).CollateralRequirements }));
        }
        public async Task <bool?> Handle(RecalculateArrangementRequestCommand message, CancellationToken cancellationToken)
        {
            //var conversionMethod = _configurationService.GetEffective("offer/fee-currency-conversion-method", "Buy to middle").Result;
            var arrangementRequest       = _arrangementRequestRepository.GetArrangementRequest(message.ApplicationNumber, message.ArrangementRequestId);
            OfferApplication application = await _applicationRepository.GetAsync(message.ApplicationNumber);

            _calculatorProvider.Calculate(arrangementRequest, application);
            //arrangementRequest.CalculateOffer(application, priceCalculator, conversionMethod);
            await _arrangementRequestRepository.UpdateArrangementRequest(arrangementRequest);

            return(await _arrangementRequestRepository.UnitOfWork.SaveEntitiesAsync());
        }
        public async Task <bool> Handle(AddSecuredDealLinkCommand message, CancellationToken cancellationToken)
        {
            var longApplicationNumber               = long.Parse(message.ApplicationNumber);
            CollateralRequirement  requirement      = _arrangementRequestRepository.GetCollateralRequirementById(longApplicationNumber, message.ArrangementRequestId, message.CollateralRequirementId);
            List <SecuredDealLink> securedDealLinks = requirement?.SecuredDealLinks ?? new List <SecuredDealLink>();
            ArrangementRequest     request          = _arrangementRequestRepository.GetArrangementRequest(longApplicationNumber, message.ArrangementRequestId);

            if (request is FinanceServiceArrangementRequest finRequest)
            {
                CurrencyConverter currencyConverter = new CurrencyConverter();
                var currencyConversionMethod        = _configurationService.GetEffective("offer/currency-conversion-method").Result;
                var pledgedValueInLoanCurrency      = currencyConverter.CurrencyConvert(message.PledgedValueInCollateralCurrency, message.ArrangementCurrency, finRequest.Currency, DateTime.Today.ToString("o", CultureInfo.InvariantCulture), currencyConversionMethod);

                var existingSecuredDealLink = securedDealLinks.Where
                                                  (x => x.ArrangementRequestId.Equals(message.ArrangementRequestId) &&
                                                  x.ApplicationNumber.Equals(message.ApplicationNumber) &&
                                                  x.ArrangementNumber.Equals(message.ArrangementNumber)).FirstOrDefault();

                if (existingSecuredDealLink != null)
                {
                    existingSecuredDealLink.PledgedValueInCollateralCurrency = message.PledgedValueInCollateralCurrency;
                    existingSecuredDealLink.PledgedValueInLoanCurrency       = pledgedValueInLoanCurrency;
                    requirement.SecuredDealLinks = securedDealLinks;
                }
                else
                {
                    securedDealLinks.Add(new SecuredDealLink
                    {
                        ApplicationNumber                = message.ApplicationNumber,
                        ArrangementNumber                = message.ArrangementNumber,
                        ArrangementRequestId             = message.ArrangementRequestId,
                        PledgedValueInCollateralCurrency = message.PledgedValueInCollateralCurrency,
                        PledgedValueInLoanCurrency       = pledgedValueInLoanCurrency
                    });
                    requirement.SecuredDealLinks = securedDealLinks;
                }
                _arrangementRequestRepository.UpdateCollateralRequirement(requirement);
                var result = await _arrangementRequestRepository.UnitOfWork.SaveEntitiesAsync();

                var msgBuilder =
                    _messageEventFactory.CreateBuilder("offer", "secured-deal-link-changed")
                    .AddHeaderProperty("application-number", message.ApplicationNumber)
                    .AddHeaderProperty("username", "ALL");

                _bus.Publish(msgBuilder.Build());
                return(result);
            }
            else
            {
                return(false);
            }
        }
        public IActionResult GetArrangementRequestForApplication([FromRoute] long applicationNumber, [FromRoute] int arrangementRequestId, [FromQuery] string include, [FromQuery] string trim)
        {
            var result = _arrangementRequestRepository.GetArrangementRequest(applicationNumber, arrangementRequestId, include, trim);

            string[] inclusions = string.IsNullOrEmpty(include) ? new string[] { } : include.Split(',');
            if (result != null)
            {
                if (!inclusions.Contains("installment-plan"))
                {
                    result.InstallmentPlan = null;
                }
                if (!inclusions.Contains("product-snapshot"))
                {
                    result.ProductSnapshot = null;
                }
            }
            if (result == null)
            {
                return(NotFound());
            }
            return(Ok(result));
        }
Esempio n. 7
0
        public async Task <bool?> Handle(AddAccountNumbersCommand message, CancellationToken cancellationToken)
        {
            ArrangementRequest arrangementRequest = _arrangementRequestRepository.GetArrangementRequest(message.ApplicationNumber, message.ArrangementRequestId);

            if (arrangementRequest == null)
            {
                return(null);
            }
            List <ArrangementAccountInfo> arrangementAccounts;

            if (arrangementRequest.Accounts == null)
            {
                arrangementAccounts = new List <ArrangementAccountInfo>();
            }
            else
            {
                arrangementAccounts = arrangementRequest.Accounts;
            }
            foreach (AccountNumbersData accountData in message.AccountNumbers)
            {
                if (accountData != null)
                {
                    _logger.LogInformation("Adding account number {accountNumbers} for {applicationNumber}", accountData.AccountNumber, message.ApplicationNumber);
                    ArrangementAccountInfo newAccount = new ArrangementAccountInfo
                    {
                        AccountNumber = accountData.AccountNumber,
                        RoleKind      = accountData.RoleKind
                    };
                    arrangementAccounts.Add(newAccount);
                }
            }
            arrangementRequest.Accounts = arrangementAccounts;
            await _arrangementRequestRepository.UpdateArrangementRequest(arrangementRequest);

            return(await _arrangementRequestRepository.UnitOfWork.SaveEntitiesAsync());
        }
Esempio n. 8
0
        public async Task <CommandStatus <bool> > Handle(UpdateArrangementRequestCommand message, CancellationToken cancellationToken)
        {
            this._logger.LogInformation("handle u command handleru");
            message.ArrangementRequest.ApplicationId        = message.ApplicationNumber;
            message.ArrangementRequest.ArrangementRequestId = message.ArrangementRequestId;
            ArrangementRequest request = _arrangementRequestRepository.GetArrangementRequest(message.ApplicationNumber, message.ArrangementRequestId);
            var conversionMethod       = _configurationService.GetEffective("offer/fee-currency-conversion-method", "Buy to middle").Result;

            if (request == null)
            {
                _logger.LogWarning("Tried to update unexisting arrangement request with application number: {0} and arrangement request id: {1}",
                                   message.ApplicationNumber, message.ArrangementRequestId);
                var e = new Exception(string.Format("Tried to update unexisting arrangement request with application number: {0} and arrangement request id: {1}",
                                                    message.ApplicationNumber, message.ArrangementRequestId));
                return(new CommandStatus <bool> {
                    Result = false, CommandResult = StandardCommandResult.BAD_REQUEST, Exception = e
                });
            }
            if (message.ArrangementRequest is TermLoanRequest termRequest &&
                termRequest.DisbursementsInfo != null && termRequest.DisbursementsInfo.Any())
            {
                var amountToBeChecked = termRequest.InvoiceAmount > 0 ? termRequest.InvoiceAmount : termRequest.Amount;
                CurrencyConverter currencyConverter = new CurrencyConverter();
                decimal           sumOfDisbursementsInPrimaryCurrency = 0;
                foreach (var item in termRequest.DisbursementsInfo)
                {
                    if (item != null && item.Amount != null)
                    {
                        continue;
                    }

                    if (item.Amount.Code == termRequest.Currency)
                    {
                        sumOfDisbursementsInPrimaryCurrency += item.Amount.Amount;
                    }
                    else
                    {
                        sumOfDisbursementsInPrimaryCurrency += currencyConverter.CurrencyConvert(item.Amount.Amount,
                                                                                                 item.Amount.Code,
                                                                                                 termRequest.Currency,
                                                                                                 DateTime.Today.ToString("o", CultureInfo.InvariantCulture),
                                                                                                 conversionMethod);
                    }

                    if (sumOfDisbursementsInPrimaryCurrency > amountToBeChecked)
                    {
                        _logger.LogWarning("Sum of disbursement info entries: {0}{2} is larger than invoice(credit) amount: {1}{2}", sumOfDisbursementsInPrimaryCurrency, amountToBeChecked, termRequest.Currency);
                        var e = new Exception(string.Format("Sum of disbursement info is above limits (invoice amount)"));
                        return(new CommandStatus <bool> {
                            Result = false, CommandResult = StandardCommandResult.BAD_REQUEST, Exception = e
                        });
                    }
                }
            }
            message.ArrangementRequest.InstallmentPlan = request.InstallmentPlan;
            if (request.ProductCode == message.ArrangementRequest.ProductCode)
            {
                message.ArrangementRequest.ProductSnapshot = request.ProductSnapshot;
                message.ArrangementRequest.ProductName     = request.ProductName;
            }
            else
            {
                return(new CommandStatus <bool> {
                    Result = false, CommandResult = StandardCommandResult.BAD_REQUEST, Exception = new Exception("An error occurred while updating arrangment - product code is wrong")
                });
                //var getProductData = new IdentifiedCommand<GetProductDataCommand, ProductData>(
                //    new GetProductDataCommand { ProductCode = message.ArrangementRequest.ProductCode }, new Guid());
                //ProductData productData = await _mediator.Send(getProductData);
                //ProductSnapshot snapshot = Mapper.Map<ProductData, ProductSnapshot>(productData);
                //message.ArrangementRequest.ProductSnapshot = snapshot;
                //message.ArrangementRequest.ProductName = snapshot.Name;
            }

            OfferApplication application =
                await _applicationRepository.GetAsync(message.ArrangementRequest.ApplicationId);

            application.PreferencialPrice = priceCalculator.HasPreferentialPrice(message.ArrangementRequest.Conditions);

            // Arrangement conditions
            request.Conditions = message.ArrangementRequest.Conditions;

            var priceCalculationParameters = request.GetPriceCalculationParameters(application);

            /*if (additionalProperties != null && additionalProperties.Keys.Count() > 0)
             * {
             *  priceCalculationParameters.AdditionalProperties = priceCalculationParameters.AdditionalProperties ?? new Dictionary<string, JToken>();
             *  priceCalculationParameters.AdditionalProperties = priceCalculationParameters.AdditionalProperties
             *      .Concat(additionalProperties
             *              .Where(k => !priceCalculationParameters.AdditionalProperties.ContainsKey(k.Key))
             *              .ToDictionary(k => k.Key, v => v.Value))
             *      .ToDictionary(k => k.Key, v => v.Value);
             * }*/

            message.ArrangementRequest = _calculatorProvider.Calculate(message.ArrangementRequest, application);
            //message.ArrangementRequest.CalculateOffer(priceCalculationParameters, priceCalculator, conversionMethod);

            await _arrangementRequestRepository.UpdateArrangementRequest(message.ArrangementRequest);

            var messageObj = _messageEventFactory.CreateBuilder("offer", "product-selection-changed")
                             .AddHeaderProperty("application-number", application.ApplicationNumber);

            messageObj = messageObj.AddBodyProperty("product-code", application.ProductCode)
                         .AddBodyProperty("product-name", application.ProductName);
            _eventBus.Publish(messageObj.Build());

            bool result = await _arrangementRequestRepository.UnitOfWork.SaveEntitiesAsync();

            await _auditClient.WriteLogEntry(AuditLogEntryAction.Update, AuditLogEntryStatus.Success, "arrangement", message.ApplicationNumber.ToString(), "Arrangement has been updated " + message.ArrangementRequestId, new { });

            StandardCommandResult commandResult = result ? StandardCommandResult.OK : StandardCommandResult.BAD_REQUEST;

            return(new CommandStatus <bool> {
                Result = result, CommandResult = commandResult
            });
        }
Esempio n. 9
0
        public async Task <bool?> Handle(AddCollateralRequirementCommand message, CancellationToken cancellationToken)
        {
            var arrangementRequest = _arrangementRequestRepository.GetArrangementRequest(message.ApplicationNumber, message.ArrangementRequestId, "collateral-requirements,product-snapshot", null);

            if (arrangementRequest == null)
            {
                return(null);
            }

            if (arrangementRequest is FinanceServiceArrangementRequest finRequest)
            {
                var fromModel       = false;
                var minimalCoverage = message.MinimalCoverage;
                var model           = finRequest.ProductSnapshot.AvailableCollateralModelsData.Where(x => x.Code.Equals(finRequest.CollateralModel)).FirstOrDefault();
                if (model != null)
                {
                    var query = model.CollateralRequirements.Where(x => x.CollateralArrangementCode.Equals(message.CollateralArrangementCode));
                    fromModel = query.Any();
                    if (fromModel)
                    {
                        var collateralRequirement = query.FirstOrDefault();
                        //minimalCoverage = collateralRequirement.MinimalCoverage;
                    }
                }
                var minimalCoverageInLoanCurrency = finRequest.Amount * (minimalCoverage / 100);
                var collateralOwner = message.CollateralOwner;
                if (string.IsNullOrEmpty(collateralOwner))
                {
                    var involvedParties = await _applicationRepository.GetInvolvedParties(message.ApplicationNumber);

                    collateralOwner = involvedParties.Where(x => x.PartyRole.Equals(PartyRole.Customer)).FirstOrDefault().PartyId.ToString();
                }
                var requirement = new CollateralRequirement
                {
                    ApplicationId                 = message.ApplicationNumber,
                    ArrangementRequestId          = message.ArrangementRequestId,
                    CollateralArrangementCode     = message.CollateralArrangementCode,
                    MinimalCoverage               = minimalCoverage,
                    MinimalCoverageInLoanCurrency = minimalCoverageInLoanCurrency,
                    ActualCoverage                = 0,
                    FromModel       = fromModel,
                    CollateralOwner = collateralOwner
                };

                if (finRequest.CollateralRequirements == null)
                {
                    finRequest.CollateralRequirements = new List <CollateralRequirement>();
                }
                requirement.CollateralRequirementId = (finRequest.CollateralRequirements.Count > 0) ? finRequest.CollateralRequirements.Max(x => x.CollateralRequirementId) + 1 : 1;
                _arrangementRequestRepository.AddCollateralRequirement(requirement);

                try
                {
                    await _auditClient.WriteLogEntry(AuditLogEntryAction.Add, AuditLogEntryStatus.Success, "collateral", message.ApplicationNumber.ToString(), "Collateral added", requirement);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Audit error in AddCollateralRequirementCommandHandler");
                }
            }
            else
            {
                return(false);
            }



            return(await _arrangementRequestRepository.UnitOfWork.SaveEntitiesAsync());
        }