示例#1
0
        public void Buy(string userName, int productId, int quantity)
        {
            if (quantity <= 0)
            {
                throw new InvalidOperationException("Quantity can't be less or equal 0");
            }

            lockService.Execute(() =>
            {
                try
                {
                    var entities    = GetAndCheckEntities(userName, productId);
                    User user       = entities.Item1;
                    Product product = entities.Item2;

                    if (product.Quantity < quantity)
                    {
                        throw new ValidationException("Not enough product to buy");
                    }

                    float userDiscount    = GetDiscount(productId);
                    decimal discountPrice = userDiscount != 0
                        ? product.Cost - ((product.Cost / 100) * (decimal)userDiscount)
                        : product.Cost;

                    decimal amount = discountPrice * quantity;

                    if (user.Amount < amount)
                    {
                        throw new ValidationException("Not enough money to buy the product");
                    }

                    transactionsRepository.Add(new Transaction()
                    {
                        Username    = user.Name,
                        ProductId   = product.Id,
                        ProductName = product.Name,
                        Quantity    = quantity,
                        Cost        = product.Cost,
                        Discount    = userDiscount,
                        SellCost    = discountPrice,
                        Amount      = amount
                    });

                    productsRepository.ChangeQuantity(productId, product.Quantity - quantity);
                    usersRepository.ChangeBalance(user.Name, user.Amount - amount);
                }
                catch (Exception ex) when(!(ex is ValidationException))
                {
                    errorsRepository.Add(new TransactionError()
                    {
                        Date        = environment.GetUtcNow(),
                        Description = ex.Message
                    });

                    throw;
                }
            });
        }
示例#2
0
        public void AddNewError()
        {
            var error = new TransactionError()
            {
                Date        = DateTime.Parse("2018-08-11"),
                Description = "Some new transaction error"
            };

            repository.Add(error);
            var expected = collectionInit.ToList();

            expected.Add(error);

            var actual = repository.GetAll().ToList();

            Assert.That(expected, Is.EquivalentTo(actual).Using(new TransactionErrorComparer()));
        }