Пример #1
0
        public async Task HandleAsync(SmartVoucherSoldEvent message)
        {
            var partner = await _partnerManagementClient.Partners.GetByIdAsync(message.PartnerId);

            var customer =
                (await _customerProfileClient.CustomerProfiles.GetByCustomerIdAsync(message.CustomerId.ToString(), true, true))?.Profile;
            var campaign = await _smartVouchersClient.CampaignsApi.GetByIdAsync(message.CampaignId);

            var receiverEmail = partner.Locations.Count == 1 ? partner.Locations.First()?.ContactPerson?.Email : null;

            await _reportHelper.AddAsync(new TransactionReport
            {
                Amount          = Money18.Create(message.Amount),
                Id              = message.PaymentRequestId,
                PartnerId       = message.PartnerId.ToString(),
                Timestamp       = message.Timestamp,
                Vertical        = partner.BusinessVertical?.ToString(),
                Info            = message.VoucherShortCode,
                Currency        = message.Currency,
                TransactionType = TxType,
                SenderEmail     = customer?.Email,
                SenderName      = $"{customer?.FirstName} {customer?.LastName}",
                CampaignName    = campaign?.Name,
                Status          = VoucherStatus,
                CampaignId      = message.CampaignId,
                PartnerName     = partner?.Name,
                ReceiverName    = partner?.Name,
                ReceiverEmail   = receiverEmail,
            });
        }
        public async Task HandleAsync(SmartVoucherUsedEvent message)
        {
            var partner = await _partnerManagementClient.Partners.GetByIdAsync(message.PartnerId);

            var customer =
                (await _customerProfileClient.CustomerProfiles.GetByCustomerIdAsync(message.CustomerId.ToString(), true, true))?.Profile;
            var campaign = await _smartVouchersClient.CampaignsApi.GetByIdAsync(message.CampaignId);

            await _reportHelper.AddAsync(new TransactionReport()
            {
                Amount          = Money18.Create(message.Amount),
                Id              = Guid.NewGuid().ToString(),
                PartnerId       = message.PartnerId.ToString(),
                Timestamp       = message.Timestamp,
                Currency        = message.Currency,
                TransactionType = TxType,
                CampaignName    = campaign?.Name,
                Status          = VoucherStatus,
                CampaignId      = message.CampaignId,
                Vertical        = partner.BusinessVertical?.ToString(),
                SenderEmail     = customer?.Email,
                SenderName      = $"{customer?.FirstName} {customer?.LastName}",
                PartnerName     = partner?.Name,
                Info            = message.VoucherShortCode,
            });
        }
 public void Money_Should_Be_Deserializable_From_Json()
 {
     JsonConvert
     .DeserializeObject <Money18>("\"10.00000\"")
     .Should()
     .Be(Money18.Create(10, 5));
 }
Пример #4
0
        public async Task <SpendRulesListResponseModel> GetSpendRulesAsync([FromQuery] PaginationRequestModel pagination)
        {
            var spendRules = await _campaignClient.Mobile.GetSpendRulesAsync(Localization.En, _mapper.Map <BasePaginationRequestModel>(pagination));

            var result = _mapper.Map <SpendRulesListResponseModel>(spendRules);

            foreach (var spendRule in result.SpendRules)
            {
                if (spendRule.BusinessVertical != BusinessVertical.Retail)
                {
                    continue;
                }

                var report = await _vouchersClient.Reports.GetSpendRuleVouchersAsync(spendRule.Id);

                spendRule.StockCount = report.InStock;
                spendRule.SoldCount  = report.Total - report.InStock;
                var rate = await _eligibilityEngineClient.ConversionRate.GetAmountBySpendRuleAsync(
                    new ConvertAmountBySpendRuleRequest()
                {
                    Amount       = Money18.Create(Math.Abs(spendRule.Price ?? 0)),
                    CustomerId   = Guid.Parse(_requestContext.UserId),
                    SpendRuleId  = spendRule.Id,
                    FromCurrency = _settingsService.GetBaseCurrencyCode(),
                    ToCurrency   = _settingsService.GetTokenName(),
                }
                    );

                spendRule.PriceInToken = rate.Amount.ToDisplayString();
            }

            return(result);
        }
        public async Task <CurrencyConverterResponse> ConvertTokensToBaseCurrencyAsync(Money18 amount)
        {
            var result = await _currencyConverterClient.Converter.ConvertTokensToBaseCurrencyAsync(amount);

            return(new CurrencyConverterResponse {
                Amount = Money18.Create(result.Amount).ToDisplayString()
            });
        }
Пример #6
0
        private static IEnumerable <Money18> Values()
        {
            yield return(Money18.Create(10.0000m));

            yield return(Money18.Create(13.00m));

            yield return(Money18.Create(10.300000m));
        }
Пример #7
0
        public void Decimal_Value_Passed__Correct_BigDecimal_Created(string a)
        {
            var d = decimal.Parse(a);

            Money18
            .Create(d)
            .Should()
            .Be(a);
        }
        public async Task WhenConversionIsMade_ConversionShoudBeValid()
        {
            var currencyRateModels = new List <CurrencyRateModel>
            {
                new CurrencyRateModel {
                    BaseAsset = _token, QuoteAsset = "USD", Rate = 2M
                },
                new CurrencyRateModel {
                    BaseAsset = "USD", QuoteAsset = "AED", Rate = 3.67M
                },
                new CurrencyRateModel {
                    BaseAsset = "USD", QuoteAsset = "NZD", Rate = 1.58M
                },
                new CurrencyRateModel {
                    BaseAsset = "AED", QuoteAsset = "USD", Rate = 0.25M
                },
                new CurrencyRateModel {
                    BaseAsset = "AED", QuoteAsset = "EUR", Rate = 0.25M
                },
                new CurrencyRateModel {
                    BaseAsset = "EUR", QuoteAsset = "GBP", Rate = 0.89M
                },
                new CurrencyRateModel {
                    BaseAsset = "EUR", QuoteAsset = "BGN", Rate = 1.96M
                },
            };

            // Arrange
            _currencyConvertorClientMock.Setup(c => c.CurrencyRates.GetAllAsync())
            .ReturnsAsync(() =>
            {
                return(currencyRateModels);
            });

            // Act
            var initialAmount     = Money18.Create(200);
            var forwardConversion = await _service.CalculateConversionRate(10, 2, _token, "BGN");

            var convertedAmount = forwardConversion * initialAmount;

            var backwardConversion = await _service.CalculateConversionRate(10, 2, "BGN", _token);

            var revertedAmount = backwardConversion * convertedAmount;

            Money18 expected = (Money18)currencyRateModels[1].Rate;

            expected *= (Money18)currencyRateModels[4].Rate;
            expected *= (Money18)currencyRateModels[6].Rate;
            expected *= (Money18)(10M / 2M);

            // Assert
            Assert.Equal(expected, forwardConversion);
            // Due to the amount of operations, 18 digits after the decimal point are exceeded
            // and thus rounded, which leads to 4 to 6 digits difference between the initial and
            // the end value
            Assert.Equal(Money18.Round(initialAmount, 10), Money18.Round(revertedAmount, 10));
        }
Пример #9
0
        public async Task GetNextWalletLinkingFeeAsync_CannotParseConfigurationValue_ReturnsZero(string configurationValue, decimal expectedParsedValue)
        {
            _configurationItemsRepositoryMock
            .Setup(x => x.GetAsync(It.IsAny <ConfigurationItemType>(), null))
            .ReturnsAsync(new ConfigurationItemEntity {
                Value = configurationValue
            });

            var sut = CreateSutInstance();

            var result = await sut.GetNextWalletLinkingFeeAsync(Guid.Parse(FakeCustomerId));

            Assert.Equal(Money18.Create(expectedParsedValue), result);
        }
        public async Task <Money18> GetCurrencyAmountInTokensAsync(decimal amount, string fromAsset, string customerId, string partnerId)
        {
            #region Validation

            if (amount < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(amount));
            }

            if (string.IsNullOrEmpty(fromAsset))
            {
                throw new ArgumentNullException(nameof(fromAsset));
            }

            #endregion

            if (amount == 0)
            {
                return(0);
            }

            var toAsset = _settingsService.GetEmaarTokenName();

            if (fromAsset == toAsset)
            {
                return(Money18.Create(amount));
            }
            else
            {
                var conversion = await _eligibilityEngineClient.ConversionRate.ConvertOptimalByPartnerAsync(
                    new ConvertOptimalByPartnerRequest
                {
                    Amount       = amount,
                    CustomerId   = Guid.Parse(customerId),
                    FromCurrency = fromAsset,
                    ToCurrency   = toAsset,
                    PartnerId    = Guid.Parse(partnerId)
                });

                if (conversion.ErrorCode != EligibilityEngineErrors.None)
                {
                    _log.Error(message: "Currency conversion error",
                               context: new { fromAsset, toAsset, error = conversion.ErrorCode.ToString() });
                }

                return(conversion.Amount);
            }
        }
Пример #11
0
        public async Task <Money18> GetRequiredAmountAsync()
        {
            using (var context = _contextFactory.CreateDataContext())
            {
                var entity = await context.TokensRequirement.FirstOrDefaultAsync();

                if (entity == null)
                {
                    await context.TokensRequirement.AddAsync(new TokensRequirementEntity
                    {
                        Amount = Money18.Create(InitialTokenAmount)
                    });

                    await context.SaveChangesAsync();

                    return(InitialTokenAmount);
                }

                return(entity.Amount);
            }
        }
Пример #12
0
        public async Task <SpendRuleDetailsModel> GetSpendRuleAsync([FromQuery] Guid spendRuleId)
        {
            var burnRule = await _campaignClient.Mobile.GetSpendRuleAsync(spendRuleId, Localization.En);

            if (burnRule == null)
            {
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.SpendRuleNotFound);
            }

            var partners = new List <PartnerModel>();

            foreach (var identifiers in burnRule.PartnerIds.Batch(10))
            {
                var tasks = identifiers
                            .Select(o => _partnerManagementClient.Partners.GetByIdAsync(o))
                            .ToList();

                await Task.WhenAll(tasks);

                partners.AddRange(tasks
                                  .Where(o => o.Result != null)
                                  .Select(o => new PartnerModel
                {
                    Id        = o.Result.Id,
                    Name      = o.Result.Name,
                    Locations = _mapper.Map <IReadOnlyCollection <LocationModel> >(o.Result.Locations)
                }));
            }

            var model = _mapper.Map <SpendRuleDetailsModel>(burnRule);

            if (burnRule.UsePartnerCurrencyRate)
            {
                var rate = await _eligibilityEngineClient.ConversionRate.GetCurrencyRateBySpendRuleIdAsync(
                    new CurrencyRateBySpendRuleRequest
                {
                    FromCurrency = _settingsService.GetTokenName(),
                    ToCurrency   = _settingsService.GetBaseCurrencyCode(),
                    CustomerId   = Guid.Parse(_requestContext.UserId),
                    SpendRuleId  = spendRuleId
                });

                model.AmountInCurrency = 1;
                model.AmountInTokens   = rate.Rate.ToDisplayString();
            }

            model.Partners = partners;

            if (model.BusinessVertical == BusinessVertical.Retail)
            {
                var report = await _vouchersClient.Reports.GetSpendRuleVouchersAsync(model.Id);

                model.StockCount = report.InStock;
                model.SoldCount  = report.Total - report.InStock;
                var rate = await _eligibilityEngineClient.ConversionRate.GetAmountBySpendRuleAsync(
                    new ConvertAmountBySpendRuleRequest()
                {
                    Amount       = Money18.Create(Math.Abs(model.Price ?? 0)),
                    CustomerId   = Guid.Parse(_requestContext.UserId),
                    SpendRuleId  = spendRuleId,
                    FromCurrency = _settingsService.GetBaseCurrencyCode(),
                    ToCurrency   = _settingsService.GetTokenName(),
                }
                    );

                model.PriceInToken = rate.Amount.ToDisplayString();
            }

            return(model);
        }