Example #1
0
        public void LoanRepository_Get_ShouldBeOk()
        {
            _loan.Id = 1;

            _expectedLoan = _repository.Get(_loan.Id);

            _expectedLoan.Should().NotBeNull();
            _expectedLoan.Id.Should().Be(1);
            _expectedLoan.Client.Should().Be("Bruno Wagner");
        }
Example #2
0
        public async Task <Loan> CreateLoan(
            Guid id,
            Guid userId,
            Guid guildId,
            Decimal amount,
            String description,
            Int32 loanPeriod = 14,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (!await _guildRepository.IsUserExists(userId, guildId, cancellationToken))
            {
                throw new UserNotFoundException(userId);
            }

            var tariff = await _guildRepository.GetTariff(userId, guildId, cancellationToken);

            var existsLoan = await _loanRepository.Get(id, cancellationToken);

            if (existsLoan != null)
            {
                if (!existsLoan.Description.Equals(description.Trim()) ||
                    existsLoan.Amount != amount ||
                    existsLoan.UserId != userId)
                {
                    throw new LoanAlreadyExistsException(existsLoan);
                }
                else
                {
                    return(existsLoan);
                }
            }

            return(new Loan(id, userId, tariff?.Id, guildId, description?.Trim(), DateTime.UtcNow.AddDays(loanPeriod), amount, 0));
        }
Example #3
0
        public Loan Get(long id)
        {
            var loan = _loanRepository.Get(id);

            loan.Client = _clientService.Get(loan.Client.Id);
            return(loan);
        }
Example #4
0
		public void CompareNlOldFees() {
			int loanid = 5146;
			long lid = 9;
			ILoanRepository loanRep = ObjectFactory.GetInstance<LoanRepository>();
			var loan = loanRep.Get(loanid);

			List<NL_LoanFees> fl = this.m_oDB.Fill<NL_LoanFees>("NL_LoanFeesGet", new QueryParameter("LoanID", lid));

			List<LoanChargesModel> list1 = new List<LoanChargesModel>();
			List<LoanChargesModel> list2 = new List<LoanChargesModel>();

			//foreach (NL_LoanFees nlFee in fl.OrderBy(f => f.AssignTime)) {
			//	list1.Add(LoanChargesModel.CompareFromNLFee(nlFee));
			//}

			//m_oLog.Debug("NL fees");
			//list1.ForEach(f => m_oLog.Debug(f));

			//foreach (LoanCharge ch in loan.Charges.OrderBy(ff => ff.Date)) {
			//	list2.Add(LoanChargesModel.CompareFromCharges(ch));
			//}

			//m_oLog.Debug("old fees fees");
			//list2.ForEach(f => m_oLog.Debug(f));

			//var list3 = list2.Except(list1, new LoanChargeModelIdComparer()).ToList();
			//m_oLog.Debug("\n DIFFERENCES----------------");
			//list3.ForEach(f => m_oLog.Debug(f));
		}
Example #5
0
		public void ApplayLateCharge() {
			int loanid = 5103;
			ILoanRepository loanRep = ObjectFactory.GetInstance<LoanRepository>();
			var loan = loanRep.Get(loanid);
			DateTime now = DateTime.UtcNow;
			ILoanOptionsRepository optRep = ObjectFactory.GetInstance<LoanOptionsRepository>();
			var loanOptions = optRep.GetByLoanId(loanid);
			//	m_oLog.Debug("loanOption={0}", loanOptions.ToString());
			if (loanOptions != null && loanOptions.AutoLateFees == false) {
				if (((loanOptions.StopLateFeeFromDate.HasValue && now >= loanOptions.StopLateFeeFromDate.Value) &&
					(loanOptions.StopLateFeeToDate.HasValue && now <= loanOptions.StopLateFeeToDate.Value)) ||
					(!loanOptions.StopLateFeeFromDate.HasValue && !loanOptions.StopLateFeeToDate.HasValue)) {
					m_oLog.Debug("not applying late fee for loan {0} - auto late fee is disabled", loanid);
					return;
				}
			}
			var charge = new LoanCharge {
				Amount = 20,
				ChargesType = new ConfigurationVariable(CurrentValues.Instance.GetByID(CurrentValues.Instance.LatePaymentCharge.ID)),
				Date = now,
				Loan = loan
			};
			m_oLog.Debug("charge={0}", charge);
			var res = loan.TryAddCharge(charge);
			m_oLog.Debug("result={0}", res);
		}
        public async Task <IActionResult> ProcessLoan(
            [FromServices] ILoanRepository repository,
            [FromRoute] Guid id,
            [FromServices] LoanProcessor processor,
            [FromServices] IQueryProcessor queryProcessor,
            CancellationToken cancellationToken)
        {
            var loan = await repository.Get(id, cancellationToken);

            if (loan == null)
            {
                throw new ApiException(HttpStatusCode.NotFound, ErrorCodes.LoanNotFound, $"Loan {id} not found");
            }

            try{
                await processor.Process(loan, cancellationToken);

                await repository.Save(loan, cancellationToken);
            }
            catch (InvalidOperationException) {
                throw new ApiException(HttpStatusCode.Conflict, ErrorCodes.IncorrectOperation, $"Incorrect loan state");
            }

            return(Ok(await queryProcessor.Process <LoanViewQuery, LoanView>(new LoanViewQuery(id), cancellationToken)));
        }
Example #7
0
 public Loan Get(Loan loan)
 {
     if (loan.Id == 0)
     {
         throw new InvalidIdException();
     }
     return(_repository.Get(loan.Id));
 }
 public Loan Get(long id)
 {
     if (id <= 0)
     {
         throw new IdentifierUndefinedException();
     }
     return(_loanRepository.Get(id));
 }
Example #9
0
		public void PayPoiinApiGetAmountToPay() {
			try {
				ILoanRepository loanRep = ObjectFactory.GetInstance<LoanRepository>();
				var loan = loanRep.Get(2070);
				var facade = new LoanPaymentFacade();
				var installment = loan.Schedule.FirstOrDefault(s => s.Id == 3773);
				var state = facade.GetStateAt(loan, DateTime.Now);
				m_oLog.Debug("Amount to charge is: {0}", state.AmountDue);
			} catch (Exception ex) {
				m_oLog.Debug(ex);
			}
		}
        /// <summary>
        /// Get Loan by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public LoanDTO Get(int id)
        {
            try
            {
                // call repository method to get loan by id
                var loan = _mapper.Map <Loan, LoanDTO>(_repository.Get(id));

                return(loan);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #11
0
        public async Task Handle(
            LoanOperationCreated message,
            CancellationToken cancellationToken)
        {
            _logger.LogInformation($"LoanOperationCreated for loan {message.LoanId} has received");
            var loan = await _loanRepository.Get(message.LoanId, cancellationToken);

            if (loan == null)
            {
                throw new InvalidOperationException($"Loan: {message.LoanId} not found");
            }
            await _loanProcessor.Process(loan, cancellationToken);

            await _loanRepository.Save(loan, cancellationToken);
        }
Example #12
0
		public void TestPaymentFacade() {
			try {
				ILoanRepository loanRep = ObjectFactory.GetInstance<LoanRepository>();
				var loan = loanRep.Get(3117);
				NL_Payments nlPayment = new NL_Payments() {
					LoanID = 1,
					Amount = 1000,
					CreatedByUserID = 1, //this._context.UserId,
					CreationTime = DateTime.UtcNow,
					PaymentMethodID = (int)NLLoanTransactionMethods.SystemRepay
				};
				var f = new LoanPaymentFacade();
				f.PayLoan(loan, "111", 1000, "11.11.11.11", DateTime.UtcNow, "system-repay", false, null, nlPayment);
			} catch (Exception ex) {
				m_oLog.Debug(ex);
			}
		}
Example #13
0
        public string AmountOfPaymentsLeft(int Id)
        {
            var GetLoan = _repository.Get(Id);

            _logger.LogDebug("Method:AmountOfPaymentsLeft");
            if (GetLoan == null)
            {
                throw new EntityNotFoundException(typeof(Loan));
            }
            _logger.LogDebug("Method:AmountOfPaymentsLeft");
            if (GetLoan.AmountOfPaymentsLeft() == 0)
            {
                throw new LoanWasClosedException(Id);
            }
            string a = System.Convert.ToString(GetLoan.AmountOfPaymentsLeft());

            return(a);
        }
Example #14
0
        public bool ApplyLateCharge(decimal amount, int loanId, int loanChargesTypeId)
        {
            DateTime now         = DateTime.UtcNow;
            var      loan        = _loans.Get(loanId);
            var      loanOptions = this.loanOptionsRepository.GetByLoanId(loanId);

            if (loanOptions != null && loanOptions.AutoLateFees == false)
            {
                if (((loanOptions.StopLateFeeFromDate.HasValue && now >= loanOptions.StopLateFeeFromDate.Value) &&
                     (loanOptions.StopLateFeeToDate.HasValue && now <= loanOptions.StopLateFeeToDate.Value)) ||
                    (!loanOptions.StopLateFeeFromDate.HasValue && !loanOptions.StopLateFeeToDate.HasValue))
                {
                    Log.InfoFormat("not applying late fee for loan {0} - auto late fee is disabled", loanId);
                    return(false);
                }
            }

            return(ApplyLateCharge(loan, amount, loanChargesTypeId, now));
        }
Example #15
0
        public void LoanSqlRepository_Update_ShouldBeOk()
        {
            //Cenário
            int    idSearch      = 1;
            Loan   loan          = _repository.Get(idSearch);
            string oldClientName = loan.ClientName;

            loan.ClientName = "Novo nome";

            //Executa
            Loan result = _repository.Update(loan);

            //Saída
            result.Should().NotBeNull();
            result.Id.Should().Be(idSearch);
            result.ClientName.Should().NotBe(oldClientName);
        }
Example #16
0
 /// <summary>
 /// Gets the list of loans.
 /// </summary>
 /// <returns>The list of loans.</returns>
 public IEnumerable <Loan> GetAllLoans()
 {
     return(loanRepository.Get(
                orderBy: q => q.OrderBy(c => c.Id),
                includeProperties: "Address"));
 }
Example #17
0
		public void ExceptPaymentTest() {

			const long loanID = 13;
			var state = new GetLoanState(351, loanID, DateTime.UtcNow, 1, false); // loanID = 17, customer = 56
			state.Execute();
			NL_Model nlLoan = state.Result;

			// loan - from DB, actual - from UI

			ILoanRepository loanRep = ObjectFactory.GetInstance<LoanRepository>();
			var loan = loanRep.Get(nlLoan.Loan.OldLoanID);
			var actual = loanRep.Get(nlLoan.Loan.OldLoanID);


			List<PaypointTransaction> loanList = loan.TransactionsWithPaypointSuccesefull;
			m_oLog.Debug("DB state:");
			loanList.ForEach(xxx => m_oLog.Debug(xxx.ToString()));

			List<PaypointTransaction> actualList = loan.TransactionsWithPaypointSuccesefull;
			var toremove = actualList.Last();
			actualList.Remove(toremove);

			m_oLog.Debug("\n\n from UI:");
			actualList.ForEach(yyy => m_oLog.Debug(yyy.ToString()));

			var removedPayments = loanList.Except(actualList);

			m_oLog.Debug("\n\n Cancelled payments:");

			foreach (PaypointTransaction transaction in removedPayments.ToList()) {

				m_oLog.Debug(transaction);

				transaction.Description = transaction.Description + "; removed amount = " + transaction.Amount;
				transaction.Interest = 0;
				transaction.Fees = 0;
				transaction.LoanRepayment = 0;
				transaction.Rollover = 0;

				transaction.Cancelled = true;
				transaction.CancelledAmount = transaction.Amount;

				transaction.Amount = 0;

				var transaction1 = transaction;

				// reset paid charges 
				loan.Charges.Where(f => f.Date <= transaction1.PostDate).ForEach(f => f.AmountPaid = 0);
				loan.Charges.Where(f => f.Date <= transaction1.PostDate).ForEach(f => f.State = null);

				IEnumerable<LoanScheduleTransaction> schTransactions = loan.ScheduleTransactions.Where(st => st.Transaction.Id == transaction1.Id);

				foreach (LoanScheduleTransaction st in schTransactions) {
					var paidSchedule = loan.Schedule.FirstOrDefault(s => s.Id == st.Schedule.Id);
					if (paidSchedule != null) {
						// reset paid rollover
						foreach (PaymentRollover r in paidSchedule.Rollovers) {
							r.PaidPaymentAmount = 0;
							r.CustomerConfirmationDate = null;
							r.PaymentNewDate = null;
							r.Status = (r.ExpiryDate.HasValue && r.ExpiryDate.Value <= DateTime.UtcNow) ? RolloverStatus.Expired : RolloverStatus.New;
						}
					}
				}
			}

			m_oLog.Debug("\n\n final state:");
			loan.TransactionsWithPaypointSuccesefull.ForEach(xx => m_oLog.Debug(xx.ToString()));
		}
Example #18
0
		public void RolloverRescheduling() {
			DateTime calcTime = DateTime.UtcNow;
			const long loanID = 17; // 21;
			GetLoanState dbState = new GetLoanState(56, loanID, calcTime, 357);
			try {
				dbState.Execute();
			} catch (NL_ExceptionInputDataInvalid nlExceptionInputDataInvalid) {
				Console.WriteLine(nlExceptionInputDataInvalid.Message);
			}
			NL_Model model = dbState.Result;
			ILoanRepository loanRep = ObjectFactory.GetInstance<LoanRepository>();
			var oldLoan = loanRep.Get(model.Loan.OldLoanID);
			var rolloverRep = ObjectFactory.GetInstance<PaymentRolloverRepository>();
			var oldRollover = rolloverRep.GetByLoanId(oldLoan.Id).FirstOrDefault();
			// copy rollover+fee+payment to NL
			if (oldRollover != null && oldRollover.PaidPaymentAmount > 0) {
				DateTime rolloverConfirmationDate = (DateTime)oldRollover.CustomerConfirmationDate;
				var fee = model.Loan.Fees.LastOrDefault();
				model.Loan.Fees.Add(new NL_LoanFees() {
					Amount = CurrentValues.Instance.RolloverCharge,
					AssignTime = rolloverConfirmationDate,
					CreatedTime = rolloverConfirmationDate,
					LoanFeeID = (fee.LoanFeeID + 1),
					LoanFeeTypeID = (int)NLFeeTypes.RolloverFee,
					AssignedByUserID = 1,
					LoanID = loanID,
					Notes = "rollover fee"
				});
				fee = model.Loan.Fees.LastOrDefault();
				model.Loan.AcceptedRollovers.Add(new NL_LoanRollovers() {
					CreatedByUserID = 1,
					CreationTime = oldRollover.Created,
					CustomerActionTime = oldRollover.CustomerConfirmationDate,
					ExpirationTime = rolloverConfirmationDate,
					IsAccepted = true,
					LoanHistoryID = model.Loan.LastHistory().LoanHistoryID,
					LoanFeeID = fee.LoanFeeID
				});
				var	transaction = oldLoan.Transactions.LastOrDefault();
				if (transaction != null) {
					model.Loan.Payments.Add(new NL_Payments() {
						Amount = transaction.Amount,
						CreatedByUserID = 1,
						CreationTime = transaction.PostDate,
						LoanID = model.Loan.LoanID,
						PaymentTime = transaction.PostDate,
						Notes = "dummy payment for rollover",
						PaymentStatusID = (int)NLPaymentStatuses.Active,
						PaymentMethodID = (int)NLLoanTransactionMethods.Manual,
						PaymentID = 15
					});
				}
			}
			/*try {
				ALoanCalculator calc = new LegacyLoanCalculator(model, calcTime);
				calc.RolloverRescheduling();
				m_oLog.Debug("{0}", calc);
				// old calc
				LoanRepaymentScheduleCalculator oldCalc = new LoanRepaymentScheduleCalculator(oldLoan, calcTime, 0);
				oldCalc.GetState();
				m_oLog.Debug("old loan State: {0}", oldLoan);
				m_oLog.Debug("\n\n====================OLD CALC InterestToPay={0}, FeesToPay={1}", oldCalc.InterestToPay, oldCalc.FeesToPay);
			} catch (Exception exception) {
				m_oLog.Error("{0}", exception.Message);
			}*/
		}