示例#1
0
        public async Task <WalletApiResponse> CreateWallet(int userId, [FromBody] CreateWalletRequest createWalletRequest)
        {
            try
            {
                if (_currencyService.HasCurrencyRate(createWalletRequest.Currency))
                {
                    var newWallet = new Wallet()
                    {
                        Currency = createWalletRequest.Currency,
                        UserId   = userId
                    };
                    _context.Wallets.Add(newWallet);
                    await _context.SaveChangesAsync();

                    return(new CreateWalletResponse(newWallet));
                }
                else
                {
                    return(new WalletApiErrorResponse($"Нельзя создать кошелек с валютой {createWalletRequest.Currency}"));
                }
            }
            catch (Exception ex)
            {
                return(new WalletApiErrorResponse(ex));
            }
        }
        public async Task <IActionResult> PutWallet(Guid id, Wallet wallet)
        {
            if (id != wallet.Id)
            {
                return(BadRequest());
            }

            _context.Entry(wallet).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!WalletExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
示例#3
0
        public async Task <IActionResult> PutTransaction(Guid CommonCode, DepositViewModel transaction)
        {
            if (CommonCode != transaction.CommonCode)
            {
                return(BadRequest());
            }
            var existingTransaction = await _context.Transactions.Where(x => x.CommonCode == CommonCode).ToListAsync();

            if (existingTransaction.Count > 0)
            {
                var existingAccount = await _context.Accounts.ToListAsync();

                var updateableTransaction = existingTransaction.Where(x => x.AccountId == x.AccountId).ToList();
                updateableTransaction.ForEach(x => x.Amount = x.Account.AccountPercent * x.Amount / 100);
                await _context.SaveChangesAsync();


                foreach (var item in existingTransaction)
                {
                    if (existingAccount.Any(x => x.AccountId == item.AccountId))
                    {
                        _context.Entry(item).State = EntityState.Modified;
                        await _context.SaveChangesAsync();
                    }
                }
            }
            else
            {
                return(NotFound());
            }

            return(NoContent());
        }
示例#4
0
        public async Task <decimal> PutMoney(long walletId, decimal sum, string currency)
        {
            var wallet = await _walletContext.Money
                         .Include(i => i.Currency)
                         .Include(i => i.Status)
                         .SingleOrDefaultAsync(s => s.Id == walletId);

            if (!IsValidPutMoneyWallet(wallet))
            {
                throw new NotActiveWalletException();
            }

            //существование валюты
            if (!IsCurrencyExist(currency))
            {
                throw new ExistCurrencyException();
            }

            sum = await ConvertSumToCurrency(sum, wallet.Currency.CurrencyName, currency);

            wallet.Sum += sum;

            await _walletContext.SaveChangesAsync();

            return(wallet.Sum);
        }
示例#5
0
        public async Task <TEntity> CreateAsync(TEntity entity)
        {
            _context.Set <TEntity>().Add(entity);
            await _context.SaveChangesAsync();

            return(entity);
        }
示例#6
0
        public async Task <int> setAmount(string id, int amount)
        {
            var query = (from i in db.Wallets
                         where i.userID == id
                         select i).FirstOrDefault();

            query.Amount += amount;
            db.Update(query);
            return(await db.SaveChangesAsync());
        }
示例#7
0
        public async Task <int> addAddress(AddressEntity address, string id)
        {
            var user = (from i in db.Users
                        where i.userID == id
                        select i).FirstOrDefault();

            user.Address = address;
            db.Update(user);
            return(await db.SaveChangesAsync());
        }
示例#8
0
        public async Task <int> AddAsync(T entity)
        {
            try
            {
                db.Set <T>().Add(entity);

                return(await db.SaveChangesAsync());
            } catch (Exception e) { }

            return(0);
        }
示例#9
0
        public async Task <bool> TryAddAccountAsync(string userId, string accountName)
        {
            if (await _walletContext.Accounts.FirstOrDefaultAsync(a =>
                                                                  a.UserId == userId && a.Name == accountName) != null)
            {
                return(false);
            }
            await _walletContext.Accounts.AddAsync(
                new AccountRecord { Name = accountName, UserId = userId });

            await _walletContext.SaveChangesAsync();

            return(true);
        }
示例#10
0
        public async Task <ActionResult <bool> > Create(CategoryRequest categoryRequest)
        {
            var userId   = HttpContext.GetUserId();
            var category = new Category
            {
                Name   = categoryRequest.Name,
                UserId = userId
            };

            _walletContext.Categories.Add(category);
            await _walletContext.SaveChangesAsync();

            return(Ok(true));
        }
示例#11
0
        public async Task <IActionResult> Add(int id, decimal sum, string cur)
        {
            Wallet wallet = _context.Wallets.FirstOrDefault(p => p.UserId == id && p.Currency == cur.ToUpper());

            if (wallet == null)
            {
                return(BadRequest("Wallet wasn't found"));
            }

            wallet.Sum += sum;
            _context.Entry(wallet).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return(RedirectToAction("Get", "Wallets", new { id = id }));
        }
示例#12
0
        public async Task ChangeOrCreateCommission([FromBody] ChangeCommissionRequest request)
        {
            var currencyId = (await _context.Currencies.FirstOrDefaultAsync(c => c.Name == request.CurrencyName)).Id;

            var userId = request.UserName == null
                ? null
                : (await _context.Users.FirstOrDefaultAsync(c => c.UserName == request.UserName)).Id;

            var commission = await _context.Commissions.FirstOrDefaultAsync(c =>
                                                                            c.OperationType == request.Type && c.CurrencyId == currencyId && c.UserId == userId);

            var dto = request.CommissionDto;

            if (commission == null)
            {
                commission =
                    CommissionManager.CreateCommission(currencyId, dto, request.Type, userId);
                await _context.AddAsync(commission);
            }
            else
            {
                commission.Rate          = dto.Rate;
                commission.Value         = dto.Value;
                commission.MaxCommission = dto.MaximalCommission;
                commission.MinCommission = dto.MinimalCommission;
                commission.Type          = dto.Type;
                commission.MaxValue      = dto.MaxOperationValue;
            }

            await _context.SaveChangesAsync();
        }
示例#13
0
        public async Task <IActionResult> PutExchange(int userid, Exchange exchange)
        {
            if (!Enum.IsDefined(typeof(CurrencyEnum), exchange?.InputCurrency) ||
                !Enum.IsDefined(typeof(CurrencyEnum), exchange?.OutputCurrency))
            {
                return(BadRequest());
            }

            var user = await _context.Users.Include(c => c.Currencies).Where(i => i.Id == userid).FirstOrDefaultAsync();

            if (user is null ||
                !user.Currencies.Any(x => x.CurrencyCode.Equals(exchange.InputCurrency)) ||
                user.Currencies.Where(x => x.CurrencyCode.Equals(exchange.InputCurrency)).First().Ammount < exchange.Ammount)
            {
                return(NotFound());
            }

            var           client   = new RestClient($"https://api.exchangeratesapi.io/latest?symbols={exchange.OutputCurrency}&base={exchange.InputCurrency}");
            var           request  = new RestRequest(Method.GET);
            IRestResponse response = await client.ExecuteAsync(request);


            var rateModel = JsonConvert.DeserializeObject <Rate>(response.Content);

            user.Currencies.First(x => x.CurrencyCode.Equals(exchange.InputCurrency)).Ammount -= exchange.Ammount;

            var rate = ParseStr(rateModel.rates.FirstOrDefault().Value);

            if (!user.Currencies.Any(x => x.CurrencyCode.Equals(exchange.OutputCurrency)))
            {
                user.Currencies.Add(new Currency()
                {
                    CurrencyCode = exchange.OutputCurrency, Ammount = Convert.ToDecimal((double)exchange.Ammount * rate)
                });
            }
            else
            {
                user.Currencies.First(x => x.CurrencyCode.Equals(exchange.OutputCurrency)).Ammount += Convert.ToDecimal((double)exchange.Ammount * rate);
            }


            _context.Update(user);
            await _context.SaveChangesAsync();

            return(Ok(response.Content));
        }
示例#14
0
        public async Task CreateCurrency(string name, CommissionDto dto)
        {
            var currency = new CurrencyRecord {
                Name = name
            };
            await _context.Currencies.AddAsync(currency);

            await _context.SaveChangesAsync();

            var deposit    = CommissionManager.CreateCommission(currency.Id, dto, OperationType.Deposit);
            var transfer   = CommissionManager.CreateCommission(currency.Id, dto, OperationType.Transfer);
            var withdrawal = CommissionManager.CreateCommission(currency.Id, dto, OperationType.Withdrawal);

            await _context.Commissions.AddRangeAsync(deposit, transfer, withdrawal);

            await _context.SaveChangesAsync();
        }
示例#15
0
 private static async Task Update <T>(string key, T value)
 {
     using (var context = new WalletContext())
     {
         var setting = context.Settings.Single(s => s.Key == key);
         setting.Value = value.ToString();
         await context.SaveChangesAsync();
     }
 }
示例#16
0
        public async Task <ActionResult <Wallet> > CreateWallet(CreateWalletCommand command)
        {
            var wallet = new Wallet
            {
                Id         = GenerateAccountNumber(),
                CustomerId = command.CustomerId,
                Name       = command.Name,
                Balance    = 0,
                Deleted    = false,
                CreatedAt  = DateTime.Now,
                Timestamp  = command.Timestamp
            };

            _context.Wallets.Add(wallet);
            await _context.SaveChangesAsync();

            return(wallet);
        }
示例#17
0
 private async Task UpdateEntityStateAsync(Contact contact, EntityState entityState)
 {
     using (var context = new WalletContext())
     {
         var contactDto = _mapper.Map <ContactDto>(contact);
         context.Contacts.Attach(contactDto);
         context.Entry(contactDto).State = entityState;
         await context.SaveChangesAsync();
     }
 }
示例#18
0
        public async Task RemoveLedgerEntriesOnBlockAsync(ulong blockId)
        {
            using (var context = new WalletContext())
            {
                var entries = await context.LedgerEntries.Where(e => e.BlockId == (long)blockId).ToListAsync();

                entries.ForEach(e => context.Entry(e).State = EntityState.Deleted);
                await context.SaveChangesAsync();
            }
        }
示例#19
0
 public async Task RemoveLedgerEntriesAsync(List <LedgerEntry> ledgerEntries)
 {
     using (var context = new WalletContext())
     {
         var dtos = _mapper.Map <List <LedgerEntryDto> >(ledgerEntries);
         context.LedgerEntries.AttachRange(dtos);
         dtos.ForEach(d => context.Entry(d).State = EntityState.Deleted);
         await context.SaveChangesAsync();
     }
 }
示例#20
0
        public async Task <IActionResult> PutTransaction(Guid TransactionCode, WithdrawViewModel transaction)
        {
            if (TransactionCode != transaction.TransactionCode)
            {
                return(BadRequest());
            }
            var existingData = await _context.Transactions.FirstOrDefaultAsync(x => x.TransactionCode == TransactionCode);

            if (existingData == null)
            {
                return(NotFound());
            }
            var existingAccount = await _context.Accounts.FirstOrDefaultAsync(x => x.AccountCode == transaction.AccountCode);

            if (existingAccount == null)
            {
                return(BadRequest());
            }

            existingData.Amount                = transaction.Amount * (-1);
            existingData.AddedTime             = (DateTime)transaction.TransactionDate;
            existingData.AccountId             = existingAccount.AccountId;
            _context.Entry(existingData).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TransactionExists(TransactionCode))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
示例#21
0
        public async Task <Contact> AddContactAsync(Contact contact)
        {
            using (var context = new WalletContext())
            {
                var contactDto = _mapper.Map <ContactDto>(contact);
                context.Contacts.Add(contactDto);
                await context.SaveChangesAsync();

                return(_mapper.Map <Contact>(contactDto));
            }
        }
示例#22
0
        public async Task AddLedgerEntryAsync(LedgerEntry ledgerEntry)
        {
            using (var context = new WalletContext())
            {
                var dto = _mapper.Map <LedgerEntryDto>(ledgerEntry);
                context.LedgerEntries.Add(dto);
                await context.SaveChangesAsync();

                ledgerEntry.Id = dto.Id;
            }
        }
示例#23
0
        public async Task <ActionResult <bool> > Create(TransactionRequest transactionRequest)
        {
            var userId      = HttpContext.GetUserId();
            var transaction = new Transaction
            {
                BankAmount = transactionRequest.BankAmount,
                CashAmount = transactionRequest.CashAmount,
                CategoryId = transactionRequest.CategoryId,
                Comment    = transactionRequest.Comment,
                Name       = transactionRequest.Name,
                Date       = transactionRequest.Date,
                Type       = (TransactionType)transactionRequest.Type,
                UserId     = userId
            };

            _walletContext.Transactions.Add(transaction);
            await _walletContext.SaveChangesAsync();

            return(Ok(true));
        }
        public async Task <bool> SaveAsync()
        {
            var isSaveSuccess = true;
            int retrnRows     = await _context.SaveChangesAsync();

            if (retrnRows == 0)
            {
                isSaveSuccess = false;
            }

            return(isSaveSuccess);
        }
示例#25
0
 public async Task UpdateLedgerEntriesAsync(List <LedgerEntry> updatedLedgerEntries)
 {
     using (var context = new WalletContext())
     {
         var dtos = _mapper.Map <List <LedgerEntryDto> >(updatedLedgerEntries);
         foreach (var dto in dtos)
         {
             context.LedgerEntries.Add(dto);
             context.Entry(dto).State = EntityState.Modified;
         }
         await context.SaveChangesAsync();
     }
 }
        public async Task <IActionResult> PutAccount(Guid AccountCode, AccountViewModel model)
        {
            if (AccountCode != model.AccountCode)
            {
                return(BadRequest());
            }
            var account = await _context.Accounts.FirstOrDefaultAsync(x => x.AccountCode == model.AccountCode);

            if (account == null)
            {
                return(BadRequest());
            }
            account.AccountCode    = model.AccountCode;
            account.AccountName    = model.AccountName;
            account.AccountPercent = model.AccountPercent;
            account.AddedTime      = DateTime.Now;
            account.IpAddress      = HttpContext.Connection.RemoteIpAddress.ToString();

            _context.Entry(account).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AccountExists(AccountCode))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
示例#27
0
        public async Task <User> Register(string login, string password)
        {
            var md5 = new MD5CryptoServiceProvider();

            var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
            var user = new User {
                Login = login, PasswordHash = hash.ByteArrayToString()
            };
            await _walletContext.Users.AddAsync(user);

            await _walletContext.SaveChangesAsync();

            return(user);
        }
示例#28
0
        public async Task AddLedgerEntriesAsync(List <LedgerEntry> ledgerEntries)
        {
            using (var context = new WalletContext())
            {
                var dtos = _mapper.Map <List <LedgerEntryDto> >(ledgerEntries);
                context.LedgerEntries.AddRange(dtos);
                await context.SaveChangesAsync();

                for (int i = 0; i < dtos.Count; i++)
                {
                    ledgerEntries[i].Id = dtos[i].Id;
                }
            }
        }
示例#29
0
        public async Task <IActionResult> PutUser(Guid UserCode, UserViewModel model)
        {
            if (UserCode != model.UserCode)
            {
                return(BadRequest());
            }

            var existingData = await _context.Users.FirstOrDefaultAsync(x => x.UserCode == UserCode);

            existingData.IpAddress    = HttpContext.Connection.RemoteIpAddress.ToString();
            existingData.AddedTime    = DateTime.Now;
            existingData.UserEmail    = model.UserEmail;
            existingData.UserImage    = model.UserImage;
            existingData.UserMobile   = model.UserMobile;
            existingData.UserName     = model.UserName;
            existingData.UserPassword = model.UserPassword;


            _context.Entry(existingData).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserExists(UserCode))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            return(NoContent());
        }
示例#30
0
        public async Task <bool> TryDoOperationAsync(string userId, TRequest request)
        {
            var currencyId = (await Context.Currencies.FirstOrDefaultAsync(c => c.Name == request.CurrencyName)).Id;
            var accountId  =
                (await Context.Accounts.FirstOrDefaultAsync(a => a.Name == request.AccountName && a.UserId == userId))
                .Id;
            var commission = await CommissionManager.CalculateCommissionAsync(userId, currencyId,
                                                                              Type, request.Value);

            var wallet = await GetOrCreateWalletAsync(currencyId, accountId);

            var operation = await CreateOperationAsync(request, currencyId, commission, accountId, wallet);

            if (operation.Commission >= operation.Value)
            {
                return(false);
            }
            if (!CheckWalletValue(wallet, operation))
            {
                return(false);
            }

            await Context.Operations.AddAsync(operation);

            await Context.SaveChangesAsync();

            var maxOperationValue =
                await CommissionManager.GetMaximalOperationValueAsync(userId, currencyId, OperationType.Deposit);

            if (maxOperationValue != 0 && maxOperationValue < operation.Value)
            {
                return(true);
            }

            return(await TryConfirmOperationAsync(operation.Id));
        }