예제 #1
0
        public void ShouldGetDepositByProcessorTransferId()
        {
            // Arrange
            var processorTransferId = "111aaa222bbb";

            var depositDto = new DepositDto
            {
                ProcessorTransferId = processorTransferId
            };

            var mpDeposit = new MpDeposit
            {
                ProcessorTransferId = processorTransferId
            };

            _mapper.Setup(m => m.Map <MpDeposit>(It.IsAny <DepositDto>())).Returns(new MpDeposit());
            _mapper.Setup(m => m.Map <DepositDto>(It.IsAny <MpDeposit>())).Returns(depositDto);
            _depositRepository.Setup(m => m.GetDepositByProcessorTransferId(processorTransferId)).Returns(mpDeposit);

            // Act
            var result = _fixture.GetDepositByProcessorTransferId(processorTransferId);

            // Assert
            Assert.Equal(processorTransferId, result.ProcessorTransferId);
        }
        public async Task <ActionResult> PostProductAsync([FromBody] DepositDto product)
        {
            try
            {
                string authHeader  = Request.Headers["Authorization"];
                string accessToken = authHeader.Substring("Bearer ".Length).Trim();

                using (var client = new HttpClient())
                {
                    var response = await client.GetUserInfoAsync(new UserInfoRequest
                    {
                        Address = _configuration["IdpProvider"] + "/connect/userinfo",
                        Token   = accessToken
                    });


                    if (response.IsError)
                    {
                        throw new Exception(response.Error);
                    }

                    //Bank getting UserInfo
                    var claims = response.Claims;
                }
                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
예제 #3
0
        public byte[] ReportDeposit(DepositDto depositDto)
        {
            var dataReport = ReportGenerationData(depositDto);

            // var result = ReportGeneration(dataReport , depositDto);
            return(dataReport);
        }
예제 #4
0
        public DepositDto SaveDeposit(DepositDto depositDto)
        {
            var mpDepositResult = _depositRepository.CreateDeposit(_mapper.Map <MpDeposit>(depositDto));
            var mappedObject    = _mapper.Map <DepositDto>(mpDepositResult);

            return(mappedObject);
        }
        public void ParameterFieldsCanBeIgnored()
        {
            var searchIndex = new FunctionIndexDefinition <DepositDto>(addPresetTransactionFields: false);
            var dto         = new DepositDto();

            Assert.Null(searchIndex.Field(nameof(dto.Approver)));
        }
예제 #6
0
        public HttpResponseMessage ReportDeposit(DepositDto deposit)
        {
            try
            {
                var    namefile              = "Отчет о депозите";
                byte[] generateExcelresult   = _bllFactory.UserBll.ReportDeposit(deposit);
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
                response.Content = new ByteArrayContent(generateExcelresult);
                response.Content.Headers.ContentType        = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = namefile + ".xls"
                };
                return(response);
            }

            catch (Exception ex)
            {
                ModelState.AddModelError("error", ex.Message);
                throw new ValidationException(ex.Message, "");
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
예제 #7
0
        ///  <summary>
        ///  Создание номера банковского счета
        /// Номер счета: 13 цифр
        /// 1-4 – это номер балансового счета, который регламентируется планом счетов бухгалтерского учета в банках.
        ///  5-12 – это номер индивидуального счета, порядок нумерации которого может определяться банками самостоятельно.Например, клиентский счет состоит из банковской кодировки клиента (первые 5 цифр из 8) и порядкового номера одного из счетов конкретного клиента(следующие 3 цифры).
        /// 13 - контрольный ключ
        ///  </summary>
        /// <param name="chartAccountsId"></param>
        /// <param name="deposit"></param>
        ///  <returns></returns>
        private string AccountСreation(ref int chartAccountsId, DepositDto deposit)
        {
            string account = String.Empty;

            // находим счет для открытия депозита
            // 1521 Срочные вклады (депозиты), размещенные в банках-резидентах
            if (deposit.DepositId == 1)
            {
                var сhartAccounts = _dalFactory.DbContext.ChartAccounts.FirstOrDefault(f => f.AccountNumber == "1521");
                if (сhartAccounts != null)
                {
                    chartAccountsId = сhartAccounts.Id;
                    account         = сhartAccounts.AccountNumber.Trim();
                }
            }
            else
            {
                var сhartAccounts = _dalFactory.DbContext.ChartAccounts.FirstOrDefault(f => f.AccountNumber == "1523");
                if (сhartAccounts != null)
                {
                    chartAccountsId = сhartAccounts.Id;
                    account         = сhartAccounts.AccountNumber.Trim();
                }
            }

            Random rand = new Random();

            while (account.Length < 12)
            {
                var temp = rand.Next(10);
                account += temp;
            }
            account += СontrolKey;
            return(account);
        }
예제 #8
0
        public void ShouldSendDepositObjectToRepoLayer()
        {
            // Arrange
            var depositDto = new DepositDto
            {
                DepositName         = "aaa",
                ProcessorTransferId = "aaa111",
                Id = 1234567
            };

            var newDepositDto = new DepositDto
            {
                DepositName         = "aaa",
                ProcessorTransferId = "aaa111",
                Id = 1234567
            };

            var newMpDeposit = new MpDeposit
            {
                Id = 1234567
            };

            _mapper.Setup(m => m.Map <MpDeposit>(It.IsAny <DepositDto>())).Returns(newMpDeposit);
            _mapper.Setup(m => m.Map <DepositDto>(It.IsAny <MpDeposit>())).Returns(newDepositDto);
            _depositRepository.Setup(r => r.CreateDeposit(It.IsAny <MpDeposit>())).Returns(newMpDeposit);

            // Act
            var result = _fixture.SaveDeposit(depositDto);

            // Assert
            Assert.NotEqual(0, result.Id);
        }
예제 #9
0
        public async Task <ICommandResult> Put(Guid id, [FromBody] DepositDto depositDto)
        {
            depositDto.AccountId = id;
            DepositAccountCommand cmd = depositDto;
            var commandResult         = await _commandBus.Submit(cmd);

            return(commandResult);
        }
        public void WillAddParametersToSearchData_ButWillNotBeSearchableByDefault()
        {
            var searchIndex = new FunctionIndexDefinition <DepositDto>(addPresetTransactionFields: false);
            var dto         = new DepositDto();

            var amountField = searchIndex.Field(nameof(dto.Amount));

            Assert.Equal(dto.Amount, amountField.GetValue(dto));
            Assert.False(amountField.IsSearchable);
        }
예제 #11
0
        public async Task Deposit(DepositDto deposit)
        {
            if (deposit.DepSum <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(deposit.DepSum), "Amount should be positive");
            }

            var card = await Context.DepositBranches
                       .Include(c => c.Card)
                       .Include(c => c.Card.CheckingBranch)
                       .Where(c => c.Card.CardId == deposit.CardId)
                       .SingleAsync();

            if (!card.Card.DepositBranchId.HasValue)
            {
                throw new InvalidOperationException("First you need to create Deposit account");
            }

            if (card.Card.CheckingBranch.Balance < deposit.DepSum)
            {
                throw new InvalidOperationException("Not enough money");
            }

            card.Card.CheckingBranch.Balance -= deposit.DepSum;

            var dep = Mapper.Map <Deposit>(deposit);

            dep.DepositBranchId = card.DepositBranchId;

            dep.Percent = dep.Term switch
            {
                1 => 8.0,
                2 => 8.0,

                3 => 9.0,
                4 => 9.0,
                5 => 9.0,

                6 => 10.0,
                7 => 10.0,
                8 => 10.0,

                9 => 10.5,
                10 => 10.5,
                11 => 10.5,

                12 => 11.0,
                _ => dep.Percent
            };


            await Context.AddAsync(dep);

            await Context.SaveChangesAsync();
        }
        public void APrimaryKeyFieldCanBeConfigured()
        {
            var searchIndex = new FunctionIndexDefinition <DepositDto>(addPresetTransactionFields: false);
            var dto         = new DepositDto();

            var idField = searchIndex.Field(nameof(dto.Id));

            Assert.True(idField.IsKey);
            Assert.True(idField.IsSearchable);
            Assert.Equal(dto.Id, idField.GetValue(dto));
        }
예제 #13
0
        public async Task<IActionResult> Deposit([FromRoute]Guid id, [FromBody]DepositDto dto, CancellationToken cancellationToken = default)
        {
            if (null == dto)
                return BadRequest();

            var currency = Currency.FromCode(dto.CurrencyCode);
            var amount = new Money(currency, dto.Amount);
            var command = new Deposit(id, amount);
            await _mediator.Publish(command, cancellationToken);
            return Ok();
        }
        public void AllowsSearchCustomisationOfParameterFields()
        {
            var searchIndex = new FunctionIndexDefinition <DepositDto>(addPresetTransactionFields: false);
            var dto         = new DepositDto();

            var currencyField = searchIndex.Field(nameof(dto.Currency));

            Assert.Equal(dto.Currency, currencyField.GetValue(dto));
            Assert.True(currencyField.IsFacetable);
            Assert.True(currencyField.IsFilterable);
        }
        public async Task <CurrentAccountDtoResult> UpdateDeposit(DepositDto depositDto, Guid userId)
        {
            var entity = await FindByUserId(userId);

            entity.Balance += depositDto.Value;

            var result = await _repository.UpdateAsync(entity, entity.Id);

            await InsertHistory(HistoricCurrentAccountMapper.Description.Deposit.Key, depositDto.Value, entity.Id);

            return(_mapper.Map <CurrentAccountDtoResult>(result));
        }
        public void UserDefinedPrimaryKeysOverridePresets()
        {
            var searchIndex = new FunctionIndexDefinition <DepositDto>(
                addPresetTransactionFields: true);

            var dto = new DepositDto();

            var uidField = searchIndex.Field(PresetSearchFieldName.tx_uid);

            Assert.False(uidField.IsKey);

            Assert.Equal(nameof(dto.Id), searchIndex.KeyField().Name);
        }
        public void CanIncludeNonParameterFieldsWithSearchFieldAttribute()
        {
            var searchIndex = new FunctionIndexDefinition <DepositDto>(addPresetTransactionFields: false);
            var dto         = new DepositDto {
                Category = "test"
            };

            var categoryField = searchIndex.Field(nameof(dto.Category));

            Assert.True(categoryField.IsFacetable);
            Assert.True(categoryField.IsFilterable);
            Assert.Equal(dto.Category, categoryField.GetValue(dto));
        }
예제 #18
0
        public async Task <IEnumerable <DepositDto> > GetDeposits([FromBody] DepositDto model)
        {
            IEnumerable <DepositDto> resultList;

            resultList = await _npRepo.GetDeposits(model.Date_Open.ToString("dd.MM.yyyy"));

            //var objDto = new List<DepositDto>();
            //foreach (var obj in objList)
            //{
            //    objDto.Add(_mapper.Map<DepositDto>(obj));
            //}
            return(resultList);
        }
예제 #19
0
 public IHttpActionResult AddDeposit(DepositDto deposit)
 {
     try
     {
         _bllFactory.UserBll.AddDeposit(deposit);
         return(Ok());
     }
     catch (Exception ex)
     {
         ModelState.AddModelError("error", ex.Message);
         return(BadRequest(ModelState));
     }
 }
예제 #20
0
        public static Deposit MapToEntity(this DepositDto dto)
        {
            if (dto == null)
            {
                return(null);
            }

            return(new Deposit
            {
                DepositeSum = dto.DepositeSum,
                Comment = dto.Comment
            });
        }
예제 #21
0
        public async Task <ActionResult> PostDeposit([FromBody] DepositDto product)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string authHeader  = Request.Headers["Authorization"];
            string accessToken = authHeader.Substring("Bearer ".Length).Trim();

            try
            {
                var endpoint = _context.Endpoints.Join(_context.Deposits,
                                                       e => e.BankId,
                                                       d => d.BankId,
                                                       (e, d) => new
                {
                    Endpoint  = e.EndpointUrl,
                    DepositId = d.Id,
                    d.BankDepositId
                })
                               .Where(e => e.DepositId == product.Id).FirstOrDefault();

                var json = JsonConvert.SerializeObject(new
                {
                    Id = endpoint.BankDepositId.Value,
                    product.DepositVariations[0].Term,
                    product.DepositVariations[0].Percent,
                    product.Sum
                });

                var content = new StringContent(json, Encoding.UTF8, "application/json");

                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    string path = endpoint.Endpoint + "Deposits";
                    HttpResponseMessage response = await client.PostAsync(path, content);

                    response.EnsureSuccessStatusCode();
                }

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
예제 #22
0
        public async Task <IActionResult> Deposit([FromBody] DepositDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            LoanVoucher v = LoanVoucher.Create(dto.LenderID, User.Identity.Name);// dto.Amount, 0.006m, dto.VoucherNumber, dto.Date);

            v.Deposit(dto.Date, dto.Amount, dto.Memo, User.Identity.Name);
            _context.LoanVouchers.Add(v);
            await _context.SaveChangesAsync();

            return(this.AlpsActionOk(v.ID));
        }
예제 #23
0
        public async Task <IList <DepositDto> > GetSomeDeposits([FromBody] DepositDto model)
        {
            var location = GetControllerActionNames();
            IList <DepositDto> resultData = null;

            try
            {
                resultData = await _npRepo.GetSomeDeposits(model.Branch, model.Date_Open.ToString("dd.MM.yyyy"), model.Code_Subject, model.File_Name, model.Currency_Code, model.Account_Type);
            }
            catch (Exception e)
            {
                _logger.LogWarn($"{location}: {e.Message} - {e.InnerException}");
            }
            return(resultData);
        }
예제 #24
0
        public async Task <IList <DepositDto> > GetDeposits([FromBody] DepositDto model)
        {
            var location = GetControllerActionNames();
            IList <DepositDto> resultData = null;

            try
            {
                resultData = await _npRepo.GetDeposits(model.Date_Open.ToString("dd.MM.yyyy"));
            }
            catch (Exception e)
            {
                _logger.LogWarn($"{location}: {e.Message} - {e.InnerException}");
            }
            return(resultData);
        }
        public async Task <IActionResult> AddDeposit([FromBody] DepositeRequest bodyPayload)
        {
            /*
             * Will receive a body with an amount and a BankUserId (/)
             * Amount deposited cannot be null or negative (/)
             * A deposit amount will first be sent to the interest rate function –the result will be saved in the database (/)
             * A record will be inserted in the deposits table as well (/)
             */

            if (bodyPayload.Amount <= 0)
            {
                return(Conflict("Amount cannot be null negative."));
            }
            try
            {
                double interestRateFuncResponse      = 0;
                HttpResponseMessage intrestFunctResp = await HTTP.PostRequest("http://interest_rate_func/api/Interest_rate_function", new { amount = bodyPayload.Amount }, CancellationToken.None); // url is to be replaced

                if (intrestFunctResp != null && intrestFunctResp.StatusCode == HttpStatusCode.OK)
                {
                    var temp = await intrestFunctResp.Content.ReadAsStringAsync();

                    interestRateFuncResponse = Convert.ToDouble(temp.Replace(".", ","));
                }
                if (interestRateFuncResponse == 0)
                {
                    return(NotFound("Interest rate function may be offline. Try again later."));
                }
                DepositDto depositToInsert = new DepositDto(bodyPayload.BankUserId, TimeStamp.GetDateTimeOffsetNowAsUnixTimeStampInSeconds(), bodyPayload.Amount);

                using (var connection = _databaseContext.Connection)
                {
                    var result = await connection.ExecuteAsync("insert into Deposit (BankUserId,CreatedAt,Amount)" +
                                                               "values (@BankUserId,@CreatedAt,@Amount)", depositToInsert);

                    if (result != 1)
                    {
                        NotFound("Deposit could not be added.");
                    }
                }

                return(Ok("Deposit added."));
            }
            catch (Exception ex)
            {
                return(NotFound(ex));
            }
        }
예제 #26
0
        public IHttpActionResult CreateDeposit(DepositDto depositDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var deposit = Mapper.Map <DepositDto, Deposit>(depositDto);

            _context.Deposits.Add(deposit);
            _context.SaveChanges();

            depositDto.Id = deposit.Id;

            return(Created(new Uri(Request.RequestUri + "/" + deposit.Id), depositDto));
        }
예제 #27
0
        /// <summary>
        /// При заключении договора должны создаваться как минимум два счета (для основной суммы и обслуживания процентов по депозиту) в соответствии с планом счетов:
        /// номер счета(13-значный, правила ниже);
        /// код счета из плана счетов(по нормам бух.учета банков РБ);
        /// активность счета из плана счетов(актив., пассив., актив.-пассив.);
        /// дебет, кредит, сальдо(остаток);
        /// название счета(ФИО клиента) и др.необходимые поля.
        /// </summary>
        /// <param name="deposit"></param>
        public void AddDeposit(DepositDto deposit)
        {
            var dublikatContract = _dalFactory.DbContext.Transactions.Any(a => a.Contract == deposit.Contract);

            if (dublikatContract)
            {
                throw new ValidationException("Данный номер доровора уже используется в системе. Задайте другой номер", "");
            }
            // начало транзакции
            using (var trans = _dalFactory.DbContext.Database.BeginTransaction())
            {
                try
                {
                    // огганизуем цикл для создания 2- х счетов
                    for (int i = 0; i < 2; i++)
                    {
                        var chartAccountsId = 0;
                        var account         = AccountСreation(ref chartAccountsId, deposit);
                        var transaction     = new Transaction
                        {
                            Account         = account,
                            CurrensyId      = deposit.CurrensyId,
                            UserId          = deposit.ClientId,
                            ChartAccountsId = chartAccountsId,
                            Balance         = i == 1 ? (decimal)deposit.Amount : 0,
                            Contract        = deposit.Contract,
                            Credit          = 0,
                            DateBegin       = deposit.DateBegin,
                            DateCreat       = DateTime.Now,
                            DepositId       = deposit.DepositId,
                            DateEnd         = deposit.DateEnd,
                            Dedet           = i == 1 ? (decimal)deposit.Amount : 0,
                            InterestDeposit = deposit.InterestDeposit,
                            status          = i != 1 ? "%" : null
                        };

                        _dalFactory.DbContext.Transactions.Add(transaction);
                    }
                    _dalFactory.DbContext.SaveChanges();
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                }
            }
        }
예제 #28
0
        public DepositDto CreateDeposit(SettlementEventDto settlementEventDto, string depositName)
        {
            var existingDeposits = _depositRepository.GetDepositNamesByDepositName(depositName);

            // append a number to the deposit, based on how many deposits already exist by that name
            // with the datetime and deposit type
            if (existingDeposits.Count < 10)
            {
                depositName = depositName + "00" + existingDeposits.Count;
            }
            else if (existingDeposits.Count >= 10 && existingDeposits.Count < 100)
            {
                depositName = depositName + "0" + existingDeposits.Count;
            }
            else if (existingDeposits.Count >= 100 && existingDeposits.Count < 999)
            {
                depositName = depositName + existingDeposits.Count;
            }
            else if (existingDeposits.Count >= 1000)
            {
                throw new Exception("Over 999 deposits for same time period");
            }

            // limit deposit name to 15 chars or less to comply with GP export
            if (depositName.Length > 14)
            {
                var truncateValue = depositName.Length - 14;
                depositName = depositName.Remove(0, truncateValue);
            }

            var depositDto = new DepositDto
            {
                // Account number must be non-null, and non-empty; using a single space to fulfill this requirement
                AccountNumber      = " ",
                BatchCount         = 1,
                DepositDateTime    = DateTime.Now,
                DepositName        = depositName,
                DepositTotalAmount = Decimal.Parse(settlementEventDto.TotalAmount.Amount),
                DepositAmount      = Decimal.Parse(settlementEventDto.TotalAmount.Amount),
                Exported           = false,
                Notes = null,
                ProcessorTransferId = settlementEventDto.Key
            };

            return(depositDto);
        }
예제 #29
0
        public IHttpActionResult Deposit(DepositDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            try
            {
                var type     = model.DepositProf.ContentType.Split('/')[1];
                var guid     = Guid.NewGuid().ToString().Replace("-", "");
                var path     = $"/ProofOfPayment/{guid}.{type}";
                var investor = _db.Investors.ToList().Find(i => i.Email == User.Identity.Name);
                var deposit  = new Deposit
                {
                    RefNo        = getRefNo(),
                    State        = DepositState.Pending,
                    ProofUrl     = path,
                    Amount       = model.Amount,
                    DepositDate  = DateTime.Now,
                    ApprovalDate = DateTime.Now,
                    PackageId    = model.PackageId,
                    InvestorId   = investor.Id
                };

                _db.Deposits.Add(deposit);
                if (!SaveProofToFolder(model.DepositProf, path))
                {
                    return(BadRequest(ModelState));
                }
                var transaction = new Transaction
                {
                    Id              = investor.Id,
                    Amount          = deposit.Amount,
                    TransactionDate = DateTime.Now,
                    TransactionType = ProcessType.Deposit,
                    RefNo           = transGetRefNo()
                };
                _db.Transactions.Add(transaction);
                _db.SaveChanges();
                return(Ok());
            }
            catch (Exception e)
            {
                return(InternalServerError(e));
            }
        }
예제 #30
0
        public async Task <DepositDto> PatchDepositAsync(int userId, DepositDto depositDto)
        {
            var user = await _dbContext.Users.FirstOrDefaultAsync(x => x.Id == userId);

            var deposit = _dbContext.Deposits.FirstOrDefault(x => x.Id == depositDto.Id);

            if (user == null || deposit == null || deposit.UserId != userId)
            {
                throw new Exception($"Not found user by id {userId} or deposit {deposit.Id} is not found \n Change data");
            }

            var depositMerge = _serviceMapper.Merge(depositDto, deposit);
            await _dbContext.SaveChangesAsync();

            var newDepositMergeMap = _serviceMapper.Map <Deposit, DepositDto>(depositMerge);

            return(newDepositMergeMap);
        }