public async Task <IActionResult> BetAsync([FromBody] BetRequest request)
        {
            Logger.LogDebug(nameof(BetAsync));

            // Validate model
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Get Player if exists
            var player = await _playerRepository.GetAsync(request.PlayerId).ConfigureAwait(false);

            // Check Player's Balance
            if (player.Balance - request.Bet < 0)
            {
                return(BadRequest(new BadRequestError($"The Player MAX. Bet Amout is {player.Balance} EUR")));
            }

            // Create new transaction
            var transaction = new Transaction
            {
                PlayerId = player.PlayerId,
                Bet      = request.Bet
            };

            // Persist Transaction
            await _transactionRepository.AddAsync(transaction).ConfigureAwait(false);

            // Re-read Player
            player = await _playerRepository.GetAsync(request.PlayerId).ConfigureAwait(false);

            return(Ok(player));
        }
Exemplo n.º 2
0
        private async Task <SubmitTransactionResponse> Deposit(Transaction tran, Client client)
        {
            client.CurrentAmount += tran.Amount;
            _clientRepository.Update(client);
            await _transactionRepository.AddAsync(tran);

            return(new SubmitTransactionResponse(true, "Deposit completed"));
        }
        public async Task CanAdd()
        {
            _logger.LogInformation("CanAdd");
            var transaction = new Transaction
            {
                Bet = 100
            };
            var newTransaction = await _transactionRepository.AddAsync(transaction).ConfigureAwait(false);

            Assert.True(newTransaction.Bet == 100);
        }
        public async Task <Transaction> CreateTransactionAsync(TransactionViewModel model)
        {
            var transaction      = ModelConverter.ConvertViewToData(model);
            var addedTransaction = await _transactionRepository.AddAsync(transaction);

            return(addedTransaction);
        }
Exemplo n.º 5
0
        public async Task <Transaction> Save(string clientID, string cpf, string accountID, string locationID, int operationType, int eventType, decimal value)
        {
            try
            {
                Transaction transaction = new Transaction
                {
                    ClientID      = clientID,
                    CPF           = cpf,
                    AccountID     = accountID,
                    LocationID    = locationID,
                    OperationType = (OperationType)operationType,
                    EventType     = (EventType)eventType,
                    Value         = value
                };

                transaction.Hash = CalculateHash(transaction);
                await _repository.AddAsync(transaction);

                await _repository.SaveAsync();

                return(transaction);
            }
            catch (Exception ex)
            { throw ex; }
        }
Exemplo n.º 6
0
        public async Task CreateTransactionAsync(string payeeEmail, CreateTransactionDto createTransactionDto)
        {
            var payee = await _userRepository.GetByEmailAsync(payeeEmail);

            var recipient = await _userRepository.GetByNameAsync(createTransactionDto.Recipient);

            ValidateCreation(payee, recipient, createTransactionDto.Amount, createTransactionDto.Recipient);

            payee.Balance     -= createTransactionDto.Amount;
            recipient.Balance += createTransactionDto.Amount;

            var transaction = new PwTransaction
            {
                Payee                     = payee,
                Recipient                 = recipient,
                ResultingPayeeBalance     = payee.Balance,
                ResultingRecipientBalance = recipient.Balance,
                Amount                    = createTransactionDto.Amount,
                TransactionDateTime       = DateTime.Now
            };

            await _transactionRepository.AddAsync(transaction);

            await _balanceHubContext.Clients.Group(recipient.Email).UpdateBalance(recipient.Balance);
        }
Exemplo n.º 7
0
        private async Task ProcessAsync(EShopType shopType)
        {
            var bufferedData = await _bufferService.GetBufferAsync(shopType);

            await _bufferService.ClearBufferAsync(shopType);

            if (bufferedData.Count == 0)
            {
                return;
            }
            var transaction = await _transactionFactory.CreateAsync(bufferedData[0].ClientCity,
                                                                    bufferedData[0].TransactionDateTime, bufferedData[0].PaymentType, bufferedData[0].ClientPostCode);

            var shop = await _shopFactory.CreateAsync(bufferedData[0].ShopName, bufferedData[0].ShopType, bufferedData[0].ShopPostCode, bufferedData[0].ShopCity);

            shop.Transactions.Add(transaction);
            transaction.Shop = shop;
            foreach (var rawData in bufferedData)
            {
                var product = await _productFactory.CreateAsync(rawData.Price, rawData.Product, rawData.Quantity);

                var transactionProduct = await _transactionProductFactory.CreateAsync(product, transaction);

                transaction.TransactionProducts.Add(transactionProduct);
                product.TransactionProducts.Add(transactionProduct);
                await _productRepository.AddAsync(product);

                await _transactionProductRepository.AddAsync(transactionProduct);
            }
            await _transactionRepository.AddAsync(transaction);

            await _shopRepository.AddAsync(shop);

            await _unitOfWork.SaveAsync();
        }
Exemplo n.º 8
0
        public async Task AddAsync(BillPaymentAddModel model)
        {
            if (model.PaymentType == Constants.TransactionType.BillPayment)
            {
                var billSummary = await _billRepository.GetSummaryAsunc(model.BillId);

                var vendorPaymentInfo = await _vendorRepository.GetPaymentInfoAsync(billSummary.VendorId);

                var billPayment = BillPaymentFactory.Create(model, vendorPaymentInfo.AccountNumber, billSummary.TotalAmount, _userId);

                await _billPaymentRepository.AddAsync(billPayment);

                await _billRepository.UpdateStatusAsync(model.BillId, Constants.BillStatus.Paid);

                //For Transaction Update
                await _transactionRepository.SetTransactionAccountIdForBill(model.BillId, model.BankAccountId, model.PaymentDate, model.Description);

                await _unitOfWork.SaveChangesAsync();
            }
            else if (model.PaymentType == Constants.TransactionType.VendorAdvancePayment)
            {
                var transaction = TransactionFactory.CreateByVendorAdvancePayment(model, model.BankAccountId, model.Amount, 0, true);
                await _transactionRepository.AddAsync(transaction);

                var transactionForDebit = TransactionFactory.CreateByVendorAdvancePayment(model, model.DebitBankAccountId, 0, model.Amount, false);
                await _transactionRepository.AddAsync(transactionForDebit);

                await _unitOfWork.SaveChangesAsync();
            }
            else if (model.PaymentType == Constants.TransactionType.AccountExpence)
            {
                var transactionforCredit = TransactionFactory.CreateByTaxPaymentByVendor(model, model.BankAccountId, model.Amount, 0, true);
                await _transactionRepository.AddAsync(transactionforCredit);

                var transactionforDebit = TransactionFactory.CreateByTaxPaymentByVendor(model, model.DebitBankAccountId, 0, model.Amount, false);
                await _transactionRepository.AddAsync(transactionforDebit);

                await _unitOfWork.SaveChangesAsync();
            }
        }
        public async Task AddAsync(InvoicePaymentAddModel model)
        {
            if (model.PaymentType == Constants.TransactionType.InvoicePayment)
            {
                var invoiceSummary = await _invoiceRepository.GetSummaryAsunc(model.InvoiceId);

                var customerPaymentInfo = await _customerRepository.GetPaymentInfoAsync(invoiceSummary.CustomerId);

                var invoicePayment = InvoicePaymentFactory.Create(model, customerPaymentInfo.AccountNumber, invoiceSummary.TotalAmount, _userId);

                await _invoicePaymentRepository.AddAsync(invoicePayment);

                await _invoiceRepository.UpdateStatusAsync(model.InvoiceId, Constants.InvoiceStatus.Paid);

                //For Transaction Update
                await _transactionRepository.SetTransactionAccountIdForInvoice(model.InvoiceId, model.BankAccountId, model.PaymentDate, model.Description);

                await _unitOfWork.SaveChangesAsync();
            }
            else if (model.PaymentType == Constants.TransactionType.CustomerAdvancePayment)
            {
                var transaction = TransactionFactory.CreateByCustomerAdvancePayment(model, model.BankAccountId, 0, model.Amount, true);
                await _transactionRepository.AddAsync(transaction);

                var transactionForCredit = TransactionFactory.CreateByCustomerAdvancePayment(model, model.CreditBankAccountId, model.Amount, 0, false);
                await _transactionRepository.AddAsync(transactionForCredit);

                await _unitOfWork.SaveChangesAsync();
            }
            else if (model.PaymentType == Constants.TransactionType.AccountIncome)
            {
                var transactionforCredit = TransactionFactory.CreateByTaxPaymentByCustomer(model, model.CreditBankAccountId, model.Amount, 0, false);
                await _transactionRepository.AddAsync(transactionforCredit);

                var transactionforDebit = TransactionFactory.CreateByTaxPaymentByCustomer(model, model.BankAccountId, 0, model.Amount, true);
                await _transactionRepository.AddAsync(transactionforDebit);

                await _unitOfWork.SaveChangesAsync();
            }
        }
Exemplo n.º 10
0
        public async Task AddAsync(TransactionModel transaction)
        {
            TransactionModel newTransaction = await _transactionRepository.AddAsync(transaction);

            await _messageSession.Publish <ITransactionRequestAdded>(message =>
            {
                message.TransactionId = newTransaction.Id;
                message.Amount        = newTransaction.Amount;
                message.SrcAccountId  = newTransaction.SrcAccountId;
                message.DestAccountId = newTransaction.DestAccountId;
                message.OperationTime = newTransaction.Date;
            });
        }
Exemplo n.º 11
0
        public async Task <ActionResult> CreateTransaction([FromBody] SaveTransactionResource newTransaction)
        {
            var transactionInDb = newTransaction.ToData();

            transactionInDb.UserName  = User.Identity.Name;
            transactionInDb.TimeStamp = DateTime.Now;

            await _transactionRepository.AddAsync(transactionInDb);

            await _unitOfWork.CompleteAsync();

            return(Ok(KidResource.FromData(await _kidRepository.GetKidAsync(newTransaction.KidId, includeRelated: true), includeRelated: true)));
        }
Exemplo n.º 12
0
        public async Task <SaveTransactionResponse> AddAsync(WalletTransaction walletTransaction)
        {
            if (walletTransaction is null)
            {
                throw new ArgumentNullException(nameof(walletTransaction));
            }

            var wallet = await _walletService.GetByGuidAsync(walletTransaction.WalletGuid);

            if (wallet is null)
            {
                return(new SaveTransactionResponse(false, "Transaction for invalid Wallet"));
            }

            var transaction = await GetByGuidAsync(walletTransaction.Guid);

            if (transaction != null)
            {
                return(new SaveTransactionResponse(true, "Transaction was already processed."));
            }

            int amountModifier;

            try
            {
                amountModifier = TransactionType.GetAmountModifierByTransactionType(walletTransaction.TransactionType);
            }
            catch (ArgumentException ex)
            {
                return(new SaveTransactionResponse(false, ex.Message));
            }

            wallet.Balance += walletTransaction.Amount * amountModifier;
            if (wallet.Balance < 0)
            {
                return(new SaveTransactionResponse(false, "Not enough gold."));
            }

            using (var transactionScope = new TransactionScope())
            {
                await _transactionRepository.AddAsync(walletTransaction);

                await _walletService.UpdateAsync(wallet);

                transactionScope.Complete();
            }

            return(new SaveTransactionResponse(true));
        }
Exemplo n.º 13
0
        public async Task <TransactionResponse> SaveAsync(Transaction transaction)
        {
            try
            {
                await _transactionRepository.AddAsync(transaction);

                await _unitOfWork.CompleteAsync();

                return(new TransactionResponse(transaction));
            }
            catch (Exception ex)
            {
                return(new TransactionResponse($"An error occurred when saving the transaction: {ex.Message}"));
            }
        }
Exemplo n.º 14
0
        public async Task <Transaction> AddTransactionAsync(string id, string appId, string description, int amount)
        {
            var transaction = await _transactions.AddAsync(id, appId, description, amount);

            using (QueryFactory db = _queryFactory.Invoke())
            {
                // https://github.com/sqlkata/querybuilder/issues/159
                await db.StatementAsync("UPDATE users SET Balance = Balance + @Amount WHERE Id = @Id", new
                {
                    Amount = amount,
                    Id     = id
                });
            }

            return(transaction);
        }
Exemplo n.º 15
0
        public async Task <AddTransactionResponse> SaveAsync(TransactionResource resource)
        {
            var transaction = _mapper.Map <TransactionResource, Transaction>(resource);

            try
            {
                await _transactionRepository.AddAsync(transaction);

                await _unitOfWork.CompleteAsync();

                return(new AddTransactionResponse(_mapper.Map <Transaction, TransactionResource>(transaction)));
            }
            catch (Exception ex)
            {
                return(new AddTransactionResponse($"An error occurred when saving the transaction: {ex.Message}"));
            }
        }
        public async Task <BaseResponse> AddAsync(AddTransactionRequest request, int accountId)
        {
            var category = await _categoryRepository.GetAsync(category => category.Id == request.CategoryId && category.AccountId == accountId);

            if (category == null)
            {
                return(new ResultResponse <TransactionDto>("Category is not found"));
            }

            if (request.TagId.HasValue)
            {
                var tag = await _tagRepository.GetAsync(tag => tag.Id == request.TagId);

                if (tag == null)
                {
                    return(new ResultResponse <TransactionDto>("Tag is not found"));
                }
            }

            if (request.SpentById.HasValue)
            {
                var spentBy = await _accountUserRepository.GetAsync(accountUser => accountUser.Id == request.SpentById);

                if (spentBy == null)
                {
                    return(new ResultResponse <TransactionDto>("Account user is not found"));
                }
            }

            var transaction = _mapper.Map <AddTransactionRequest, Transaction>(request);
            var loggedUser  = await _authenticationService.GetLoggedUserAsync();

            var accountUser = await _accountUserRepository.GetAsync(accountUser => accountUser.UserId == loggedUser.User.Id && accountUser.AccountId == category.AccountId);

            transaction.CreatedBy = accountUser;
            await _transactionRepository.AddAsync(transaction);

            await _unitOfWork.SaveChangesAsync();

            return(new BaseResponse());
        }
Exemplo n.º 17
0
            public async Task <Response> Handle(Request request,
                                                CancellationToken cancellationToken)
            {
                Transaction transaction = new(
                    Guid.NewGuid(),
                    TransactionType.Expense,
                    request.Username,
                    request.Amount,
                    request.DateTime,
                    request.CategoryId,
                    request.Description
                    );

                var addedTransaction = await _transactionRepository.AddAsync(transaction);

                await _transactionRepository.SaveChangesAsync();

                var response = _mapper.Map <Response>(addedTransaction);

                return(response);
            }
        public async Task <string> ExecuteAsync(
            Guid transactionId,
            string from,
            string to,
            BigInteger transactionAmount,
            BigInteger gasAmount,
            bool includeFee)
        {
            var gasPrice = await _blockchainService.EstimateGasPriceAsync();

            var nonce = await _nonceService.GetNextNonceAsync(from);

            var transactionData = _blockchainService.BuildTransaction
                                  (
                from: from,
                to: to,
                amount: transactionAmount,
                gasAmount: gasAmount,
                gasPrice: gasPrice,
                nonce: nonce
                                  );

            await _transactionRepository.AddAsync(Transaction.Create
                                                  (
                                                      transactionId: transactionId,
                                                      from: from,
                                                      to: to,
                                                      amount: transactionAmount,
                                                      gasAmount: gasAmount,
                                                      gasPrice: gasPrice,
                                                      includeFee: includeFee,
                                                      nonce: nonce,
                                                      data: transactionData
                                                  ));

            return(transactionData);
        }
Exemplo n.º 19
0
        public async Task <IActionResult> Create(string request)
        {
            var transactionDto = _objectJsonConverter.ConvertTransactionJsonDataToObj(request);

            if (transactionDto != null)
            {
                if (transactionDto.TransactionAmount < 0)
                {
                    _logger.LogInformation($"Error:Transaction with value {transactionDto.TransactionAmount} for account id {transactionDto.AccountId}  is less than zero, which is not allowed");
                    return(Content("Negative amounts cannot be transacted"));
                }
                if (!string.IsNullOrEmpty(transactionDto.TransactionCurrency) && transactionDto.TransactionCurrency != "GBP")
                {
                    transactionDto = await _transactionLogic.SetTransactionAmountToBaseCurrency(transactionDto);
                }
                var result = await _transactionLogic.SetAccountBalanceForCreditAndDebit(transactionDto);

                if (!result)
                {
                    _logger.LogInformation($"Error:Transaction with value {transactionDto.TransactionAmount} for account id {transactionDto.AccountId}  is greater than Available Balance");
                    return(Content("Transacted Amount is more than the available balance"));
                }
                transactionDto.LastUpdated = DateTime.Now;

                var transactionAdded = await _transactionRepository.AddAsync(_mapper.Map <Transaction>(transactionDto));

                if (transactionAdded != null)
                {
                    _logger.LogInformation($"Info:Transaction with value {transactionDto.TransactionAmount} for account id {transactionDto.AccountId}  created successfully");
                    return(Ok(_mapper.Map <TransactionDto>(transactionAdded)));
                }

                return(NotFound());
            }
            return(Content("Transaction is empty"));
        }
Exemplo n.º 20
0
        public async Task <TransactionResponse> RegisterTransactionAsync(Transaction transaction, CancellationToken cancellationToken)
        {
            _logger.LogDebug("{method} started for transaction {transactionId}.", nameof(RegisterTransactionAsync), transaction.Id);
            using (await padlock.ReaderLockAsync(cancellationToken).ConfigureAwait(true))
            {
                await EnsurePlayerExistsAsync(transaction.PlayerId, cancellationToken).ConfigureAwait(false);
            }

            _logger.LogTrace("{method}: Player {playerId} found.", nameof(RegisterTransactionAsync), transaction.PlayerId);
            using (await padlock.WriterLockAsync(cancellationToken).ConfigureAwait(true))
            {
                var transactionResponse = await _transactionResponseCache
                                          .GetAsync(transaction.Id, cancellationToken)
                                          .ConfigureAwait(false);

                if (transactionResponse is not null)
                {
                    _logger.LogTrace("{method}: Transaction found in persistent cache. Returning response. {transactionResponse}", nameof(RegisterTransactionAsync), transactionResponse);
                    return(transactionResponse);
                }

                try
                {
                    _logger.LogTrace("{method}: Transaction not found in cache. Returning response.", nameof(RegisterTransactionAsync));
                    var wallet = await _wallets
                                 .GetExistingAsync(transaction.PlayerId, cancellationToken)
                                 .ConfigureAwait(false);


                    if (transaction.TransactionType == TransactionType.Stake)
                    {
                        if (transaction.Amount > wallet.Balance)
                        {
                            _logger.LogTrace("{method}: LowBalanceException. Transaction {transactionId} will be as rejected registered.", nameof(RegisterTransactionAsync), transaction.PlayerId);
                            throw new LowBalanceException($"Low balance exception for the Player {transaction.PlayerId}");
                        }

                        wallet.Balance -= transaction.Amount;
                    }
                    else
                    {
                        wallet.Balance += transaction.Amount;
                    }

                    transactionResponse = new TransactionResponse
                    {
                        TransactionId      = transaction.Id,
                        ResponseStatusCode = StatusCodes.Status202Accepted
                    };

                    await _transactionResponseCache
                    .AddAsync(transactionResponse, cancellationToken)
                    .ConfigureAwait(false);

                    await _transactions.AddAsync(transaction, cancellationToken).ConfigureAwait(false);

                    await _unitOfWork.CommitAsync(cancellationToken).ConfigureAwait(false);

                    _logger.LogTrace("{method}: Transaction {transactionId} registered successfully. The new balance is {balance}.", nameof(RegisterTransactionAsync), transaction.PlayerId, wallet.Balance);
                }
                catch (Exception)
                {
                    transactionResponse = new TransactionResponse
                    {
                        TransactionId      = transaction.Id,
                        ResponseStatusCode = StatusCodes.Status403Forbidden
                    };

                    await _transactionResponseCache
                    .AddAsync(transactionResponse, cancellationToken)
                    .ConfigureAwait(false);

                    await _unitOfWork.CommitAsync(cancellationToken).ConfigureAwait(false);

                    _logger.LogTrace("{method}: Transaction {transactionId} was not executed.", nameof(RegisterTransactionAsync), transaction.PlayerId);
                }

                _logger.LogDebug("{method} finished for transaction {transactionId}.", nameof(RegisterTransactionAsync), transaction.Id);
                return(transactionResponse);
            }
        }
Exemplo n.º 21
0
        public async Task <ProductSelectionResult> Selection(ProductSelection productSelection)
        {
            ProductSelectionResult productSelectionResult = new ProductSelectionResult();

            try
            {
                if (productSelection == null)
                {
                    productSelectionResult.Code    = 1;
                    productSelectionResult.Message = "null parameter";
                    return(productSelectionResult);
                }

                var product = await _productRepository.GetByIdAsync(productSelection.Slot);

                if (product == null)
                {
                    productSelectionResult.Slot    = productSelection.Slot;
                    productSelectionResult.Code    = 1;
                    productSelectionResult.Message = $"Slot: {productSelection.Slot} Message: Slot bulunamadı!";

                    return(productSelectionResult);
                }

                if (!product.IsAvailable)
                {
                    productSelectionResult.Slot    = productSelection.Slot;
                    productSelectionResult.Code    = 1;
                    productSelectionResult.Message = "Ürün Bitti!";
                    return(productSelectionResult);
                }

                if (product.NumberOfProducts < productSelection.SelectedPieces)
                {
                    productSelectionResult.Slot    = productSelection.Slot;
                    productSelectionResult.Code    = 1;
                    productSelectionResult.Message = $"NumberOfProducts: {product.NumberOfProducts} SelectedPieces: {productSelection.SelectedPieces}";
                    return(productSelectionResult);
                }

                var totalAmount = productSelection.SelectedPieces * product.PriceOfProduct;

                var campaings = await _campaingRepository.GetAllAsync();

                if (campaings != null && campaings.Count > 0)
                {
                    var campaing = campaings.Where(a => a.Slot == productSelection.Slot).FirstOrDefault();
                    if (campaing != null)
                    {
                        totalAmount += totalAmount * campaing.DiscountRatio;
                    }
                }

                TransactionEntity transactionEntity = new TransactionEntity();
                transactionEntity.Slot              = productSelection.Slot;
                transactionEntity.SelectedPieces    = productSelection.SelectedPieces;
                transactionEntity.TransactionAmount = totalAmount;

                transactionEntity = await _transactionRepository.AddAsync(transactionEntity);

                productSelectionResult.Slot          = productSelection.Slot;
                productSelectionResult.TransactionId = transactionEntity.Id;
                productSelectionResult.TotalAmount   = totalAmount;
                productSelectionResult.Code          = 0;
                productSelectionResult.Message       = "Başarılı işlem";
            }
            catch (Exception ex)
            {
                //logging
                productSelectionResult.Slot    = productSelection.Slot;
                productSelectionResult.Code    = 1;
                productSelectionResult.Message = "Hata oluştu!";
            }

            return(productSelectionResult);
        }
Exemplo n.º 22
0
        public async Task <TransactionResponse> SaveAsync(Guid playerId, IEnumerable <Transaction> transactions)
        {
            if (transactions.Count() == 0)
            {
                return(new TransactionResponse("Empty transactions"));
            }

            var existingPlayer = await _playerRepository.FindByIdAsync(playerId);

            if (existingPlayer == null)
            {
                return(new TransactionResponse("Player not exist"));
            }

            try
            {
                TransactionStatistics transactionStatistics = new TransactionStatistics();

                // traverse through transactions
                foreach (var transaction in transactions)
                {
                    try
                    {
                        transaction.PlayerId = playerId;
                        transaction.Player   = existingPlayer;

                        var existingTransaction = await _transactionRepository.FindByIdAsync(transaction.TransactionId);

                        if (existingTransaction == null)
                        {
                            // execute transaction
                            await _transactionCommand.ExecuteAction(transaction);

                            // create a new instance of the transaction in the repository
                            transaction.Status = ETransactionStatus.Succeed;
                            await _transactionRepository.AddAsync(transaction);

                            // update successfully processed transaction statistics
                            transactionStatistics.AppliedTransactions.Add(transaction.TransactionId);
                        }
                        else
                        {
                            // duplicated transaction => return cached result
                            if (existingTransaction.Status == ETransactionStatus.Succeed)
                            {
                                transactionStatistics.AppliedTransactions.Add(transaction.TransactionId);
                            }
                            else
                            {
                                transactionStatistics.FailedTransactions.Add(new FailedTransaction {
                                    TransactionId = transaction.TransactionId, Message = existingTransaction.Message
                                });
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // update failed transaction statistics
                        transactionStatistics.FailedTransactions.Add(new FailedTransaction {
                            TransactionId = transaction.TransactionId, Message = ex.Message
                        });
                        transaction.Status  = ETransactionStatus.Failed;
                        transaction.Message = ex.Message;
                        await _transactionRepository.AddAsync(transaction);
                    }
                }

                // story changes
                await _unitOfWork.CompleteAsync();

                return(new TransactionResponse(transactionStatistics));
            }
            catch (Exception ex)
            {
                return(new TransactionResponse($"An error occurred when saving the transaction: {ex.Message}"));
            }
        }
Exemplo n.º 23
0
        public async Task AddAsync(InvoiceAddModel model)
        {
            // var items = (await _itemRepository.GetAsync(model.Items)).ToList();

            //model.TotalAmount = items.Sum(x => x.Rate);

            //model.Tax = items.Where(x => x.IsTaxable).Sum(x => x.Rate * x.SalesTax.TaxPercentage / 100);

            //var customer = await _customerRepository.GetAsync(model.CustomerId);

            //if (customer.Discount != null)
            //{
            //    model.Discount = model.TotalAmount * customer.Discount / 100;
            //    model.TotalAmount = model.TotalAmount - (model.Discount ?? 0);
            //}

            //if (model.Tax != null)
            //{
            //    model.TotalAmount = model.TotalAmount + (model.Tax ?? 0);
            //}
            model.LineAmountSubTotal = model.Items.Sum(x => x.LineAmount);

            var count = await _invoiceRepository.getCount();

            //await _invoiceRepository.AddAsync(InvoiceFactory.Create(model, _userId, items));


            var invoice = InvoiceFactory.Create(model, _userId, count);
            await _invoiceRepository.AddAsync(invoice);

            await _unitOfWork.SaveChangesAsync();

            var transaction = TransactionFactory.CreateByInvoice(invoice);
            await _transactionRepository.AddAsync(transaction);

            await _unitOfWork.SaveChangesAsync();

            var itemsList = (model.Items.GroupBy(l => l.BankAccountId, l => new { l.BankAccountId, l.LineAmount })
                             .Select(g => new { GroupId = g.Key, Values = g.ToList() })).ToList();

            foreach (var item in itemsList)
            {
                var id     = item.GroupId;
                var amount = item.Values.Sum(x => x.LineAmount);

                var itemsData = TransactionFactory.CreateByInvoiceItemsAndTax(invoice, id, amount);
                await _transactionRepository.AddAsync(itemsData);

                await _unitOfWork.SaveChangesAsync();
            }

            var taxlistList = (model.Items.GroupBy(l => l.TaxBankAccountId, l => new { l.TaxBankAccountId, l.TaxPrice })
                               .Select(g => new { GroupId = g.Key, Values = g.ToList() })).ToList();

            foreach (var tax in taxlistList)
            {
                if (tax.GroupId > 0)
                {
                    var id     = tax.GroupId;
                    var amount = tax.Values.Sum(x => x.TaxPrice);

                    var taxData = TransactionFactory.CreateByInvoiceItemsAndTax(invoice, id, amount);
                    await _transactionRepository.AddAsync(taxData);

                    await _unitOfWork.SaveChangesAsync();
                }
            }
        }
        public async Task<string> BuildTransactionAsync(BigInteger amount, BigInteger fee, string fromAddress, BigInteger gasPrice, bool includeFee, Guid operationId, string toAddress)
        {
            #region Validation
            
            if (amount <= 0)
            {
                throw new ArgumentException("Amount should be greater then zero.", nameof(amount));
            }

            if (fee <= 0)
            {
                throw new ArgumentException("Fee should be greater then zero.", nameof(fee));
            }
            
            if (gasPrice <= 0)
            {
                throw new ArgumentException("Gas price should be greater then zero.", nameof(gasPrice));
            }

            if (!await AddressValidator.ValidateAsync(fromAddress))
            {
                throw new ArgumentException("Address is invalid.", nameof(fromAddress));
            }

            if (!await AddressValidator.ValidateAsync(toAddress))
            {
                throw new ArgumentException("Address is invalid.", nameof(toAddress));
            }

            #endregion

            var operationTransactions = (await _transactionRepository.GetAllAsync(operationId));
            var initialTransaction = operationTransactions.OrderBy(x => x.BuiltOn).FirstOrDefault();

            if (initialTransaction != null)
            {
                return initialTransaction.TxData;
            }

            var nonce = await _ethereum.GetNextNonceAsync(fromAddress);
            
            var txData = _ethereum.BuildTransaction
            (
                toAddress,
                amount,
                nonce,
                gasPrice,
                Constants.EtcTransferGasAmount
            );

            await _transactionRepository.AddAsync(new BuiltTransactionDto
            {
                Amount = amount,
                BuiltOn = DateTime.UtcNow,
                Fee = fee,
                FromAddress = fromAddress,
                GasPrice = gasPrice,
                IncludeFee = includeFee,
                Nonce = nonce,
                OperationId = operationId,
                State = TransactionState.Built,
                ToAddress = toAddress,
                TxData = txData
            });

            _chaosKitty.Meow(operationId);

            return txData;
        }