Beispiel #1
0
        public async Task <int> CreateAsync(TransactionCreateDto transactionCreateDto)
        {
            var user   = this.loggedInUserInfoProvider.GetLoggedInUser();
            var wallet = await this.walletRepository.GetByIdAsync(transactionCreateDto.WalletId);

            TransactionCategory category = null;

            if (transactionCreateDto.CategoryId != null)
            {
                category =
                    await this.transactionCategoryRepository.GetByIdAsync(
                        transactionCreateDto.CategoryId.Value);
            }

            var transactionType = TransactionCategoryType.Expense;

            if (category != null)
            {
                transactionType = category.Type;
            }

            if (wallet.UserId != user.Id)
            {
                throw new ForbiddenException("Wallet not belong to user");
            }

            if (wallet.Balance < transactionCreateDto.Amount)
            {
                throw new BadRequestException("Balance in wallet not enought");
            }

            var newTransaction = new Transaction(transactionType)
            {
                Amount     = transactionCreateDto.Amount,
                UserId     = user.Id,
                WalletId   = transactionCreateDto.WalletId,
                CategoryId = transactionCreateDto.CategoryId,
                CreatedAt  = transactionCreateDto.CreatedAt,
            };

            if (transactionType == TransactionCategoryType.Expense)
            {
                wallet.Balance -= transactionCreateDto.Amount;
            }
            else if (transactionType == TransactionCategoryType.Income)
            {
                wallet.Balance += transactionCreateDto.Amount;
            }
            else
            {
                throw new NotSupportedException("Transaction category type not supported");
            }

            this.transactionRepository.Create(newTransaction);
            this.walletRepository.Update(wallet);
            await this.wmDbTransaction.CommitAsync();

            return(newTransaction.Id);
        }
Beispiel #2
0
        public async Task <int> Create(TransactionCreateDto dto, string userId)
        {
            var createdTransaction = _mapper.Map <TransactionDbEntity>(dto);

            await _dbContext.Transactions.AddAsync(createdTransaction);

            await _dbContext.SaveChangesAsync();

            return(createdTransaction.Id);
        }
        public TransactionDto Create(TransactionCreateDto model)
        {
            var entry = new Transaction {
                Customer    = _context.Customers.Single(x => x.CustomerId == model.CustomerId),
                CustomerId  = model.CustomerId,
                Status      = model.Status,
                Description = model.Description
            };

            _context.Transactions.Add(entry);
            _context.SaveChanges();
            return(_mapper.Map <TransactionDto>(entry));
        }
        public async Task <ActionResult> CreateAsync([FromForm] TransactionCreateDto dto)
        {
            var userId = HttpContext.User.Identity.Name;

            if (string.IsNullOrEmpty(userId))
            {
                return(NotFound("user not found"));
            }
            dto.SenderId = userId;
            var transaction = await _service.CreateTransactionAsync(dto);

            await _service.SendRefresh(dto.RecipientId);

            return(CreatedAtAction("Create", new { id = transaction.Id }, transaction));
        }
Beispiel #5
0
        public ActionResult <TransactionReadDto> PostTodoItem(TransactionCreateDto transactionCreateDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var transactionModel = _mapper.Map <Transaction>(transactionCreateDto);

            _repository.CreateTransaction(transactionModel);
            _repository.SaveChanges();

            var transactionReadDto = _mapper.Map <TransactionReadDto>(transactionModel);

            return(CreatedAtRoute(nameof(GetTransactionById), new { Id = transactionReadDto.Id }, transactionReadDto));
        }
        public IActionResult AddFunds(
            [FromBody] TransactionCreateDto transaction)
        {
            if (transaction == null)
            {
                return(BadRequest());
            }

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

            if (transaction.SavingAccountId != 0 && !_repository.SavingAccountExits(transaction.SavingAccountId))
            {
                return(NotFound());
            }

            if (transaction.SavingAccountId != 0)
            {
                // AdHoc Transaction, add funds to Saving account
                _repository.AddFund(transaction.Amount, transaction.SavingAccountId);
            }
            else
            {
                _repository.AddFund(transaction.Amount);
            }

            if (!_repository.Save())
            {
                return(StatusCode(500, "A problem happend when adding funds. Please try again."));
            }
            else
            {
                return(NoContent());
            }
        }
Beispiel #7
0
        public async Task <Transaction> CreateTransactionAsync(TransactionCreateDto dto)
        {
            var balances = GetCurrentBalances(dto.SenderId, dto.RecipientId);

            var senderBalance = balances.Where(x => x.UserId == dto.SenderId).FirstOrDefault();

            if (senderBalance.CurrentBalance < dto.Amount)
            {
                throw new Exception("Cancel! Sum of transaction is greater of balance");
            }
            senderBalance.DateUpdate     = DateTime.Now;
            senderBalance.CurrentBalance = senderBalance.CurrentBalance - dto.Amount;

            var recipientBalance = balances.Where(x => x.UserId == dto.RecipientId).FirstOrDefault();

            recipientBalance.DateUpdate     = DateTime.Now;
            recipientBalance.CurrentBalance = recipientBalance.CurrentBalance + dto.Amount;

            var outcoming = CreteFromDto(dto);

            outcoming.Type    = Models.Enum.TransactionType.Credit;
            outcoming.Balance = senderBalance.CurrentBalance;

            var incomming = CreteFromDto(dto);

            incomming.Type    = Models.Enum.TransactionType.Debit;
            incomming.Balance = recipientBalance.CurrentBalance;

            _balanceService.Update(recipientBalance);
            _balanceService.Update(senderBalance);
            await AddAsync(incomming);
            await AddAsync(outcoming);
            await CommitAsync();

            return(outcoming);
        }
        public async Task <IActionResult> CreateAsync([FromBody] TransactionCreateDto transactionCreateDto)
        {
            int id = await this.transactionService.CreateAsync(transactionCreateDto);

            return(Ok(new { Id = id }));
        }
 public async Task <IActionResult> Create([FromBody] TransactionCreateDto dto)
 => await GetResponse(async (userId) =>
                      new ApiResponseViewModel(true, "Transaction Created Successfully", await _service.Create(dto, userId)));
Beispiel #10
0
        public ActionResult <TransactionDto> CreateTransaction([FromBody] TransactionCreateDto transaction)
        {
            try
            {
                var product = productMockService.GetProductById(transaction.ProductId);

                if (product == null)
                {
                    return(NotFound("Product with specified id does not exist."));
                }

                if (!productMockService.HasEnoughProducts(transaction.ProductId, transaction.ProductsQuantity))
                {
                    return(StatusCode(StatusCodes.Status406NotAcceptable, "There is no enough products."));
                }

                if (!transportTypeMockService.TransportTypeExistsById(transaction.TransportTypeId))
                {
                    return(NotFound("Transport type with specified id does not exist."));
                }


                Transaction transactionEntity = mapper.Map <Transaction>(transaction);

                transactionEntity.BuyingDateTime = DateTime.Now;

                Transaction createdTransaction = transactionRepository.CreateTransaction(transactionEntity);
                var         valid = transactionValidator.Validate(createdTransaction);
                if (!valid.IsValid)
                {
                    return(BadRequest(valid.Errors));
                }

                //Trazimo usera da bismo dobili id naloga sa kog treba da skinemo novac
                var user = userMockService.GetAccounByUserId(transaction.BuyerId);

                if (user == null)
                {
                    return(NotFound("User with specified id does not exist."));
                }

                //Trazimo nalog sa kog treba da skinemo novac
                var account = accountMockService.getAccountById(user.AccountId);

                //Iznos koji treba da skinemo sa naloga
                decimal amount = product.Price * transaction.ProductsQuantity;

                if (account == null)
                {
                    return(NotFound("User does not have account."));
                }

                if (account.AccountBalance < amount)
                {
                    return(StatusCode(StatusCodes.Status406NotAcceptable, "You do not have enough money to buy this product."));
                }

                TransactionChargeDto charge = new TransactionChargeDto {
                    AccountId = account.AccountId, Amount = amount
                };

                //Naplacujemo
                bool charged = accountMockService.charge(charge);

                //Proveravamo da li je naplaceno
                if (!charged)
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while charging, contact administration"));
                }

                //Smanjujemo broj proizvoda na lageru
                TransactionReduceStockDto purchase = new TransactionReduceStockDto {
                    ProductId = transaction.ProductId, Quantity = transaction.ProductsQuantity
                };

                bool reducedStock = productMockService.ProductPurchased(purchase);

                if (!reducedStock)
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while stock reducing, contact administration"));
                }

                transactionRepository.SaveChanges();

                logger.Log(LogLevel.Information, $"requestId: {Request.HttpContext.TraceIdentifier}, previousRequestId:No previous ID, Message: Transaction successfully created.");

                string location = linkGenerator.GetPathByAction("GetTransaction", "Transaction", new { transactionId = createdTransaction.TransactionId });

                return(Created(location, mapper.Map <TransactionDto>(createdTransaction)));
            }
            catch (Exception e)
            {
                logger.Log(LogLevel.Warning, $"requestId: {Request.HttpContext.TraceIdentifier}, previousRequestId:No previous ID, Message: Transaction unsuccessfully created.", e);
                return(StatusCode(StatusCodes.Status500InternalServerError, "Create error " + e.Message));
            }
        }
Beispiel #11
0
        public async Task <IActionResult> CreateTransactions(int id, [FromBody] TransactionCreateDto newTransaction)
        {
            var inventory = await _invRepo.GetInventory(id);

            if (inventory == null)
            {
                return(NotFound(new { error = new string[] { "Inventory not Found" } }));
            }

            var transactionType = await _transRepo.GetTransactionType(newTransaction.Transaction);

            if (transactionType == null)
            {
                return(NotFound(new { error = new string[] { "Transaction Type not Found" } }));
            }

            if (newTransaction.Quantity <= 0)
            {
                ModelState.AddModelError("error", "Quantity Should be greater than Zero");
            }


            if (string.Equals(transactionType.Action, "add"))
            {
                inventory.Quantity += newTransaction.Quantity;

                if (inventory.Quantity > inventory.ThresholdCritical && inventory.Quantity <= inventory.ThresholdWarning)
                {
                    var status = await _invRepo.GetInventoryStatusByName("Warning");

                    inventory.Status = status;
                }
                else if (inventory.Quantity > 0 && inventory.Quantity <= inventory.ThresholdCritical)
                {
                    var status = await _invRepo.GetInventoryStatusByName("Critical");

                    inventory.Status = status;
                }
                else if (inventory.Quantity > inventory.ThresholdWarning)
                {
                    var status = await _invRepo.GetInventoryStatusByName("OK");

                    inventory.Status = status;
                }
            }

            if (string.Equals(transactionType.Action, "subtract"))
            {
                var quantity = inventory.Quantity - newTransaction.Quantity;

                if (quantity >= 0)
                {
                    inventory.Quantity = quantity;

                    if (inventory.Quantity > inventory.ThresholdCritical && inventory.Quantity <= inventory.ThresholdWarning)
                    {
                        var status = await _invRepo.GetInventoryStatusByName("Warning");

                        inventory.Status = status;
                    }
                    else if (inventory.Quantity > 0 && inventory.Quantity <= inventory.ThresholdCritical)
                    {
                        var status = await _invRepo.GetInventoryStatusByName("Critical");

                        inventory.Status = status;
                    }
                    else if (inventory.Quantity == 0)
                    {
                        var status = await _invRepo.GetInventoryStatusByName("No Stock");

                        inventory.Status = status;
                    }
                }
                else
                {
                    ModelState.AddModelError("error", "Must not make quantity Negative");
                }
            }

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

            var transaction = new InventoryTransaction
            {
                TransactionType = transactionType,
                Quantity        = newTransaction.Quantity,
                Details         = newTransaction.Details,
                TimeStamp       = DateTime.Now,
                Inventory       = inventory
            };

            _transRepo.Add(transaction);

            if (await _transRepo.Save())
            {
                var transactionToReturn = _mapper.Map <TransactionCreatedDto>(transaction);

                return(Ok(transactionToReturn));
            }
            else
            {
                return(BadRequest(new { error = new string[] { "Error saving transaction" } }));
            }
        }