public async Task <BalanceDTO> UpdateBalance(BalanceDTO newBalance)
        {
            Balance balanceToSave = new Balance()
            {
                CurrentBalance = JsonDocument.Parse(newBalance.Balance),
                SubmitedDate   = newBalance.SubmitedDate
            };

            DateTime currentDate    = newBalance.SubmitedDate;
            Position latestPosition = await _unitOfWork.Positions.GetLatestPosition();

            if (latestPosition.SubmitedDate.Year == currentDate.Year &&
                latestPosition.SubmitedDate.Month == currentDate.Month &&
                latestPosition.SubmitedDate.Day == currentDate.Day)
            {
                balanceToSave.Position = latestPosition;
                _unitOfWork.Balances.Add(balanceToSave);
                _unitOfWork.SaveChanges();
                return(newBalance);
            }
            else
            {
                Position newPosition = new Position()
                {
                    SubmitedDate = currentDate,
                };

                _positionService.AddNewPosition(newPosition);
                balanceToSave.Position = await _unitOfWork.Positions.GetLatestPosition();

                _unitOfWork.Balances.Add(balanceToSave);
                _unitOfWork.SaveChanges();
                return(newBalance);
            }
        }
示例#2
0
        public List <BalanceDTO> GetUserBalance(int userId)
        {
            var balances = db.Balances.Where(o => o.UserId == userId).ToList();

            var balanceTypes = db.BalanceTypes.ToList();

            var result = new List <BalanceDTO>();

            balances.ForEach(o =>
            {
                var b = new BalanceDTO()
                {
                    balance = o.Amount.Value,
                    id      = o.Id,
                };
                var t  = balanceTypes.FirstOrDefault(p => p.Id == o.TypeId);
                b.type = new BalanceTypeDTO()
                {
                    id        = t.Id,
                    code      = t.Code,
                    precision = t.Precision,
                };

                result.Add(b);
            });

            return(result);
        }
示例#3
0
        public BalanceDTO AddBalance(BalanceDTO obj)
        {
            obj.CreationDate = DateTime.Now;
            var LastBalance = unitofwork.Balance.GetAll().Where(x => x.StoreId == obj.StoreId).OrderBy(y => y.CreationDate).Last();
            List <ItemBalanceDTO> itemList = new List <ItemBalanceDTO>();

            foreach (var i in LastBalance.ItemBalances)
            {
                ItemBalanceDTO item    = new ItemBalanceDTO();
                int            balance = this.CalculateItemBalanceForStore(i.ItemId, obj.StoreId, LastBalance.BalanceDate);
                item.ItemId   = i.ItemId;
                item.Quantity = i.Quantity + balance;
                itemList.Add(item);
            }
            obj.itemList = itemList.ToArray();
            var entity = Mapper.Map <BalanceDTO, Balance>(obj);

            unitofwork.Balance.Add(entity);

            try
            {
                unitofwork.SaveChanges();

                return(Mapper.Map <Balance, BalanceDTO>(entity));
            }

            catch
            {
                return(Mapper.Map <Balance, BalanceDTO>(entity));
            }
        }
示例#4
0
        public async Task <List <int> > AddTransaction(BalanceDTO balanceDTO)
        {
            List <int> result = new List <int>();

            if (balanceDTO.Amount <= 0)
            {
                result.Add(AddTransaccionResponse.MinorZero);

                return(result);
            }

            var balances = await _context.Balances.ToListAsync();

            var balancesDTO = _mapper.Map <List <BalanceDTO> >(balances);
            var response    = _logicMethods.AddTransaction(balancesDTO, balanceDTO.Type, balanceDTO.Amount);

            if (response)
            {
                var balanceEntity = _mapper.Map <Balance>(balanceDTO);
                balanceEntity.Date = DateTime.Now;

                _context.Balances.Add(balanceEntity);
                await _context.SaveChangesAsync();

                result.Add(AddTransaccionResponse.Created);
                result.Add(balanceEntity.Id);

                return(result);
            }
            result.Add(AddTransaccionResponse.ToMuchWithDrawAmount);
            return(result);
        }
示例#5
0
        public async Task <FxTransactionDTO> InsertSalesTransaction(FxTransactionDTO newTransaction)
        {
            Staff staffMember = new Staff()
            {
                Department = "sales",
                Email      = "*****@*****.**",
                FirstName  = "Henri",
                LastName   = "Haka",
                KeycloakId = "asdasdadasd",
            };

            FX fxTransaction = new FX()
            {
                ApprovedBy     = staffMember,
                BoughtAmount   = newTransaction.SoldAmount * newTransaction.ExchangeRate,
                BoughtCurrency = newTransaction.BoughtCurrency,
                CreatedDate    = newTransaction.CreatedDate,
                Bank           = newTransaction.Customer,
                ExchangeRate   = newTransaction.ExchangeRate,
                SoldAmount     = newTransaction.SoldAmount,
                SoldCurrency   = newTransaction.SoldCurrency,
                Position       = await _unitOfWork.Positions.GetLatestPosition()
            };
            BalanceDTO updatedBalance = await _balanceService.PrepareBalance(newTransaction);

            _unitOfWork.FxTransactions.Add(fxTransaction);
            _unitOfWork.SaveChanges();
            return(newTransaction);
        }
示例#6
0
        public async Task <double> GetWalletBalanceByAssetId(string walletId, string assetId)
        {
            string path     = $"/api/wallets/{walletId}/balances/{assetId}";
            var    response = await Consumer.ExecuteRequestCustomEndpoint(BaseUrl.ApiV2BaseUrl + path, Helpers.EmptyDictionary, null, Method.GET);

            double balance;

            switch (response.Status)
            {
            case HttpStatusCode.OK:
                BalanceDTO walletBalanceDTO = JsonUtils.DeserializeJson <BalanceDTO>(response.ResponseJson);
                balance = walletBalanceDTO.Balance;
                break;

            case HttpStatusCode.NotFound:            // Service returns not found if there is no balance for the asset
            case HttpStatusCode.InternalServerError: // Service returns InternalServerError and message "Message": "Technical problem" if there is no balance for the asset
                balance = 0;
                break;

            default:
                throw new Exception($"Cannot get balance of Asset: {assetId} for WalletId: {walletId}. Response: {response.ResponseJson}");
            }


            return(balance);
        }
示例#7
0
        private MessageDTO CreateMessage(PaymentDTO payment, BalanceDTO balance)
        {
            var content = $"There is insufficient balance on account {balance.Id} to repay payment {payment.Id}. Required balance: {payment.Amount}, current balance: {balance.Amount}";

            return(new MessageDTO {
                UserId = balance.UserId, Content = content
            });
        }
示例#8
0
 /// <summary>
 /// Actualiza un Balance por medio del id
 /// </summary>
 public void Update(string id, BalanceDTO entity)
 {
     using (var dbContextScope = new TiendaDbContext())
     {
         _repository.Update(this.GetEntity(entity), id);
         dbContextScope.SaveChanges();
     }
 }
示例#9
0
        /// <summary>
        /// Metodo que dada una entidad devuelve su DTO
        /// </summary>
        /// <param name="entity">Entidad de la cual se requiere el DTO</param>
        /// <returns>DTO para la entidad pasada por parametro</returns>
        private BalanceDTO GetDTO(Balance entity)
        {
            BalanceDTO dto = new BalanceDTO();

            dto.BalanceId = entity.BalanceId;
            this.SetDTOExtras(entity, ref dto);

            return(dto);
        }
示例#10
0
        public async Task UpdateBalance()
        {
            AccountEntity testAccount = (AccountEntity)await this.AccountRepository.TryGetAsync(this.TestAccountId1);

            Assert.NotNull(testAccount);
            BalanceDTO accountBalance = testAccount.BalancesParsed.Where(b => b.Asset == this.TestAsset1).FirstOrDefault();

            Assert.NotNull(accountBalance);



            //Execute balance update
            double newBalance      = accountBalance.Balance + 1.0;
            string balanceUpdateId = Guid.NewGuid().ToString();

            await this.Consumer.Client.UpdateBalanceAsync(balanceUpdateId, this.TestAccountId1, this.TestAsset1, newBalance);

            BalanceUpdate message = (BalanceUpdate)await this.WaitForRabbitMQ <BalanceUpdate>(o => o.id == balanceUpdateId);

            Assert.True(message.type == "BALANCE_UPDATE");

            BalanceUpdate.ClientBalanceUpdate balance = message.balances.Where(m => m.id == this.TestAccountId1).FirstOrDefault();
            Assert.True(balance != null);
            Assert.True(balance.asset == this.TestAsset1);
            Assert.True(balance.oldBalance == accountBalance.Balance);
            Assert.True(balance.newBalance == newBalance);
            Assert.True(balance.oldReserved == balance.newReserved);

            AccountEntity checkTestAccount = (AccountEntity)await this.AccountRepository.TryGetAsync(this.TestAccountId1);

            BalanceDTO checkAccountBalance = checkTestAccount.BalancesParsed.Where(b => b.Asset == this.TestAsset1).FirstOrDefault();

            Assert.True(checkAccountBalance.Balance == newBalance);

            //reverse balance update
            string reverseBalanceUpdateId = Guid.NewGuid().ToString();

            await this.Consumer.Client.UpdateBalanceAsync(reverseBalanceUpdateId, this.TestAccountId1, this.TestAsset1, accountBalance.Balance);

            message = (BalanceUpdate)await this.WaitForRabbitMQ <BalanceUpdate>(o => o.id == reverseBalanceUpdateId);

            Assert.True(message.type == "BALANCE_UPDATE");

            balance = message.balances.Where(m => m.id == this.TestAccountId1).FirstOrDefault();
            Assert.True(balance != null);
            Assert.True(balance.asset == this.TestAsset1);
            Assert.True(balance.oldBalance == newBalance);
            Assert.True(balance.newBalance == accountBalance.Balance);
            Assert.True(balance.oldReserved == balance.newReserved);

            checkTestAccount = (AccountEntity)await this.AccountRepository.TryGetAsync(this.TestAccountId1);

            checkAccountBalance = checkTestAccount.BalancesParsed.Where(b => b.Asset == this.TestAsset1).FirstOrDefault();

            Assert.True(checkAccountBalance.Balance == accountBalance.Balance);
        }
示例#11
0
 /// <summary>
 /// Servicio que permite insertar una nueva entidad: Balance (Balance)
 /// </summary>
 /// <param name="entity">DTO de la entidad a insertar</param>
 /// <param name="user">Usuario que ejecuta la inserción</param>
 /// <returns>Se devulve el DTO de la entidad creada con el id asignado</returns>
 public BalanceDTO Insert(BalanceDTO dto, string user)
 {
     using (var dbContextScope = new TiendaDbContext())
     {
         Balance entity = GetEntity(dto);
         entity = _repository.Insert(entity, user);
         dbContextScope.SaveChanges();
         return(GetDTO(entity));
     }
 }
示例#12
0
        public BalanceDTO UserToAddBalance(int userId)
        {
            User       user       = efu.Users.Get(userId);
            BalanceDTO balanceDTO = new BalanceDTO();

            balanceDTO.UserId  = userId;
            balanceDTO.Balance = user.Balance;

            return(balanceDTO);
        }
        public Task <List <int> > AddTransaction(BalanceDTO balanceDTO)
        {
            List <int> data = new List <int>
            {
                0,
                1
            };

            return(Task.FromResult(data));
        }
示例#14
0
        public IHttpActionResult PostBalance(BalanceDTO obj)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var result = Service.AddBalance(obj);

            return(Ok(result));
        }
示例#15
0
        public IHttpActionResult GetGenericLastBalance()
        {
            BalanceDTO entity = Service.GetGenericLastBalance();

            if (entity == null)
            {
                return(NotFound());
            }

            return(Ok(entity));
        }
示例#16
0
        public IHttpActionResult GetLastBalance(int storeId)
        {
            BalanceDTO entity = Service.GetLastBalance(storeId);

            if (entity == null)
            {
                return(NotFound());
            }

            return(Ok(entity));
        }
示例#17
0
        public ActionResult Balance()
        {
            int userId = Convert.ToInt32(Request.Cookies["UserId"].Value);

            UserService us         = new UserService();
            BalanceDTO  balanceDTO = us.UserToAddBalance(userId);

            var config           = new MapperConfiguration(cfg => cfg.CreateMap <BalanceDTO, BalanceViewModel>());
            var mapper           = new Mapper(config);
            var balanceModelView = mapper.Map <BalanceViewModel>(balanceDTO);

            return(View(balanceModelView));
        }
        public async Task <IActionResult> SubmitSalesTransaction([FromBody] SalesTransactionDTO newTransaction)
        {
            try
            {
                BalanceDTO updatedBalance = await _salesTransactionService.InsertSalesTransaction(newTransaction);

                return(Ok(updatedBalance));
            }
            catch
            {
                return(BadRequest("Sale was not submited successfully"));
            }
        }
示例#19
0
        public async Task GetWalletBalanceByWalletAndAssetId()
        {
            string url      = ApiPaths.WALLETS_BASE_PATH + "/" + this.TestWallet.Id + "/balances/" + this.TestAssetId;
            var    response = await this.Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, null, Method.GET);

            Assert.True(response.Status == HttpStatusCode.OK);
            WBalanceDTO parsedResponse = JsonUtils.DeserializeJson <WBalanceDTO>(response.ResponseJson);

            BalanceDTO accountBalance = this.TestWalletAccount.BalancesParsed.Where(b => b.Asset == this.TestAssetId).FirstOrDefault();

            Assert.NotNull(accountBalance);
            Assert.True(parsedResponse.Balance == accountBalance.Balance);
        }
示例#20
0
        public async Task <IActionResult> UpdateBalance([FromBody] BalanceDTO balance)
        {
            try
            {
                BalanceDTO updatedBalance = await _balanceService.UpdateBalance(balance);

                return(Ok(updatedBalance));
            }
            catch
            {
                return(BadRequest("Something went wrong"));
            }
        }
示例#21
0
        public async Task <IActionResult> GetCurrentPosition()
        {
            try
            {
                DateTime   today           = DateTime.Now;
                BalanceDTO startingBalance = await _balanceService.GetLatestBalance(today);

                return(Ok(startingBalance));
            }
            catch
            {
                return(BadRequest("The data has not been imported correctly from the database"));
            }
        }
示例#22
0
        public async Task GetWalletBalanceForAsset()
        {
            string url = $"{ApiPaths.BALANCES_WALLET_BALANCES}/{this.TestClient.Account.Id}/{Constants.BALANCES_ASSET_ID}";

            var response = await Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, null, Method.GET);

            Assert.True(response.Status == HttpStatusCode.OK);

            BalanceDTO parsedResponse = JsonUtils.DeserializeJson <BalanceDTO>(response.ResponseJson);

            Assert.True(parsedResponse.AssetId == Constants.BALANCES_ASSET_ID);
            Assert.True(parsedResponse.Balance == Constants.BALANCES_ASSET_AMOUNT);
            Assert.True(parsedResponse.Reserved == 0);
        }
        public Usuario ConsultarBalanceginAsync(string email)
        {
            var result = _context.Usuarios.Where(x => x.Email == email).FirstOrDefault();

            if (result != null)
            {
                BalanceDTO balance = new BalanceDTO();
                balance.id      = result.Id;
                balance.Nombre  = result.Nombre;
                balance.Email   = result.Email;
                balance.Balance = result.Balance.ToString();
            }

            return(result);
        }
        public async Task <ActionResult <BalanceDTO> > PostBalance(BalanceDTO balanceDTO)
        {
            var result = await _repositoryBalance.AddTransaction(balanceDTO);

            if (result[0].Equals(AddTransaccionResponse.MinorZero))
            {
                return(BadRequest("Error, Monto menor a cero"));
            }

            if (result[0].Equals(AddTransaccionResponse.ToMuchWithDrawAmount))
            {
                return(BadRequest("Error, Monto de retiro mayor al saldo actual"));
            }

            return(CreatedAtAction("GetBalance", new { id = result[1] }, balanceDTO));
        }
示例#25
0
        public bool UpdateBalance(BalanceDTO obj)
        {
            Balance entity = new Balance();

            entity = Mapper.Map <BalanceDTO, Balance>(obj);
            unitofwork.Balance.Update(entity);
            try
            {
                unitofwork.SaveChanges();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
示例#26
0
        public IHttpActionResult PutBalance(int id, BalanceDTO obj)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != obj.ID)
            {
                return(BadRequest());
            }

            Service.UpdateBalance(obj);


            return(StatusCode(HttpStatusCode.NoContent));
        }
        public async Task <BalanceDTO> GetStartingBalance(DateTime today)
        {
            Position position = await _unitOfWork.Positions.GetLatestPosition();

            BalanceDTO startingBalance = new BalanceDTO();

            if (position.SubmitedDate.Year == today.Year &&
                position.SubmitedDate.Month == today.Month &&
                position.SubmitedDate.Day == today.Day)
            {
                Balance currentStartingBalance = await _unitOfWork.Balances.GetStartingBalanceByPositionId(position.Id);

                startingBalance.SubmitedDate = currentStartingBalance.SubmitedDate;
                startingBalance.Balance      = Utility.JsonToString(currentStartingBalance.CurrentBalance);
            }
            return(startingBalance);
        }
示例#28
0
        public async Task GetWalletTradeBalanceByAssetId()
        {
            string url      = ApiPaths.WALLETS_TRADING_BALANCES_PATH + "/" + this.TestAssetId;
            var    response = await this.Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, null, Method.GET);

            Assert.True(response.Status == HttpStatusCode.OK);
            WBalanceDTO parsedResponse = JsonUtils.DeserializeJson <WBalanceDTO>(response.ResponseJson);

            AccountEntity entity = await this.AccountRepository.TryGetAsync(this.TestClientId) as AccountEntity;

            Assert.NotNull(entity);
            BalanceDTO entityBalance = entity.BalancesParsed.Where(b => b.Asset == this.TestAssetId).FirstOrDefault();

            Assert.NotNull(entityBalance);

            Assert.True(entityBalance.Balance == parsedResponse.Balance);
        }
        public async Task <List <BalanceDTO> > GetBalances()
        {
            List <Position> positions = await _unitOfWork.Positions.GetPositions();

            List <BalanceDTO> balances = new List <BalanceDTO>();

            foreach (var position in positions)
            {
                Balance balance = await _unitOfWork.Balances.GetLatestBalanceByPositionId(position.Id);

                BalanceDTO newBalance = new BalanceDTO()
                {
                    Balance      = Utility.JsonToString(balance.CurrentBalance),
                    SubmitedDate = balance.SubmitedDate,
                };
                balances.Add(newBalance);
            }
            return(balances);
        }
        public async Task <List <BalanceDTO> > GetTodayBalances()
        {
            Position position = await _unitOfWork.Positions.GetLatestPosition();

            List <Balance> balances = await _unitOfWork.Balances.GetBalances(position.Id);

            List <BalanceDTO> balancesToReturn = new List <BalanceDTO>();

            foreach (var balance in balances)
            {
                var newBalance = new BalanceDTO()
                {
                    SubmitedDate = balance.SubmitedDate,
                    Balance      = Utility.JsonToString(balance.CurrentBalance)
                };
                balancesToReturn.Add(newBalance);
            }
            return(balancesToReturn);
        }