internal static void AddRepayment(this Repayment item) { try { string sql = "INSERT INTO Repayment (Id, CreditId, RepaymentDate, PlanningDate, Performed, Amount)" + " VALUES ( @Id, @CreditId, @RepaymentDate, @PlanningDate, @Performed, @Amount)"; ConnectionClient.ConOpen(); using (SqlCommand cmd = new SqlCommand(sql, ConnectionClient.connection)) { cmd.Parameters.AddWithValue("@Id", item.Id); cmd.Parameters.AddWithValue("@CreditId", item.CreditId); cmd.Parameters.AddWithValue("@RepaymentDate", item.RepaymentDate); cmd.Parameters.AddWithValue("@PlanningDate", item.PlanningDate); cmd.Parameters.AddWithValue("@Performed", item.Performed); cmd.Parameters.AddWithValue("@Amount", item.Amount); cmd.ExecuteNonQuery(); ConnectionClient.ConClose(); } } catch (SqlException e) { errorMes.ErrorSQL(e.Message); ConnectionClient.ConClose(); } catch (Exception e) { errorMes.ErrorSQL(e.Message); ConnectionClient.ConClose(); } }
/// <summary> /// Обновление данных /// </summary> /// <param name="item"></param> internal static void EditRepayment(this Repayment item) { try { string sql = "UPDATE Repayment SET CreditId = @CreditId , RepaymentDate = @RepaymentDate, PlanningDate = @PlanningDate, Performed = @Performed, Amount = @Amount WHERE Id = @Id"; ConnectionClient.ConOpen(); using (SqlCommand cmd = new SqlCommand(sql, ConnectionClient.connection)) { cmd.Parameters.AddWithValue("@Id", item.Id); cmd.Parameters.AddWithValue("@CreditId", item.CreditId); cmd.Parameters.AddWithValue("@RepaymentDate", item.RepaymentDate); cmd.Parameters.AddWithValue("@PlanningDate", item.PlanningDate); cmd.Parameters.AddWithValue("@Performed", item.Performed); cmd.Parameters.AddWithValue("@Amount", item.Amount); cmd.ExecuteNonQuery(); ConnectionClient.ConClose(); } } catch (SqlException e) { errorMes.ErrorSQL(e.Message); }catch (Exception e) { errorMes.ErrorSQL(e.Message); } finally { ConnectionClient.ConClose(); } }
internal static void LoadRepayment() { try { string sql = "SELECT * FROM Repayment"; lock (o) { ConnectionClient.ConOpen(); using (SqlCommand commmand = new SqlCommand(sql, ConnectionClient.connection)) { SqlDataReader reader = commmand.ExecuteReader(); while (reader.Read()) { Repayment repay = new Repayment((int)reader["Id"], (int)reader["CreditId"], (DateTime)reader["RepaymentDate"], (DateTime)reader["PlanningDate"], (bool)reader["Performed"], (decimal)reader["Amount"]); CreditRepository.RepaymentsList.Add(repay); } } ConnectionClient.ConClose(); } } catch (SqlException e) { errorMes.ErrorSQL(e.Message); } catch (Exception e) { errorMes.ErrorSQL(e.Message); } finally { ConnectionClient.ConClose(); } }
private static async Task RemainingLoansAsync(string phoneNumber) { var credits = await Credit.GetRemainingLoanAsync(phoneNumber); var creditsList = new List <string>(); credits.ForEach(credit => creditsList.Add($"{credit} ")); creditsList.Add("Go back "); var selectedIndex = 0; while (true) { Shred(); Console.SetCursorPosition(2, 2); selectedIndex = Ui.ComboBox(creditsList, selectedIndex); if (selectedIndex == creditsList.Count - 1) { break; } var repayments = await Repayment.GetCreditRepaymentsAsync(credits[selectedIndex].Id); var repaymentsList = new List <string>(); repayments.ForEach(repayment => repaymentsList.Add($"{repayment} ")); repaymentsList.Add("Back"); Shred(); Console.SetCursorPosition(2, 2); Ui.ComboBox(repaymentsList); } }
public void PrintQuote(Repayment repayment) { console.WriteLine($"Requested amount: £{repayment.Principal.Amount:#}"); console.WriteLine($"Rate: {repayment.AnnualInterestRate.Annual:P1}"); console.WriteLine($"Monthly repayment: £{repayment.MonthlyRepayment.Amount:#.00}"); console.WriteLine($"Total repayment: £{repayment.TotalRepayment.Amount:#.00}"); }
public void RepaymantServieThrowsRepaymantCalculationExceptionCase1() { /* * Given the following inputs: * Loan amount = 290000 * Annual Interest rate = 7.5 (note this is the annual interest rate and we require a monthly repayment figure) * Term years = 0 * Term months = 0 * This should cause an error to occur in the calculation which must be trapped and displayed to the user in a friendly manner */ try { Repayment paymentTest = new Repayment() { AnnualInterestRate = 7.5, LoanAmount = 290000, TermMonths = 0, TermYears = 0 }; var monthlyPaymant = paymentService.MonthlyPaymentAmount(paymentTest); var totalToBePaid = paymentService.AmountPaidBack(paymentTest); } catch (Exception e) { int?c = null; if (e is RepaymantCalculationException) { c = (e as RepaymantCalculationException).code; } Assert.That(c, Is.EqualTo(100)); } }
// Total amount pay back when the completion of total repaymants public double AmountPaidBack(Repayment payment) { if (payment.TermMonths <= 0 && payment.TermYears <= 0) { throw new RepaymantCalculationException("Minimum Repaymant term should be one month or more", ExceptionCode.REPAYMENT_TERM_EQUALS_TO_0); } var repaymentMonths = (payment.TermYears * 12) + payment.TermMonths; return(Math.Round((MonthlyPaymentAmount(payment) * repaymentMonths), 2, MidpointRounding.AwayFromZero)); }
public void print_a_repayment_details_quote() { var repayment = new Repayment(principal, monthlyRepayment, totalRepayment, annualInterestRate); var quotePrinter = new QuotePrinter(console.Object); quotePrinter.PrintQuote(repayment); console.Verify(a => a.WriteLine("Requested amount: £1")); console.Verify(a => a.WriteLine("Rate: 10.0%")); console.Verify(a => a.WriteLine("Monthly repayment: £2.22")); console.Verify(a => a.WriteLine("Total repayment: £3333.33")); }
private Repayment CreateRepaymentRecord(RepaymentUpload repayment, decimal amount, int parentId) { var record = new Repayment { CustomerId = repayment.CustomerId, SeasonId = (int)repayment.SeasonId, Date = repayment.Date, Amount = amount, ParentId = parentId }; _repaymentRepository.Insert(record); return(record); }
private string FormatQuote(Repayment repayment) { if (repayment != null) { var quoteFormatter = new StringBuilder(); quoteFormatter.AppendLine($"Requested amount: £{repayment.RequestedAmount}"); quoteFormatter.AppendLine($"Annual Interest Rate: {Math.Round(repayment.AnnualInterestRateInPercent, 1)}%"); quoteFormatter.AppendLine($"Monthly repayment: £{Math.Round(repayment.MonthlyRepayment,2)}"); quoteFormatter.AppendLine($"Total repayment: £{Math.Round(repayment.TotalRepayment,2)}"); return(quoteFormatter.ToString()); } return(string.Empty); }
public void Return_RepaymentQuote_When_Processing_Request() { // Arrange var termInMonths = 36; var expectedRepayment = new Repayment(1000, 7.0m, 30.78m, 1108.10m); _interestCalculatorMock.Setup(calculator => calculator.CalculateTotalAnnualInterest(It.IsAny <IEnumerable <Lender> >(), _amount)).Returns(7.0m); _repaymentCalculatorMock.Setup(calculator => calculator.Calculate(7.0m, _amount, termInMonths)) .Returns(expectedRepayment); // Act var repaymentQuote = _repaymentService.Process(_fileName, _amount); // Assert var expectedRepaymentQuote = CreateRepaymentQuote(); Assert.Equal(expectedRepaymentQuote, repaymentQuote); }
// get Payment amount // The formula for calculating the monthly payment amount is in WIKI // https://en.wikipedia.org/wiki/Mortgage_calculator public double MonthlyPaymentAmount(Repayment payment) { if (payment.TermMonths <= 0 && payment.TermYears <= 0) { throw new RepaymantCalculationException("Minimum Repaymant term should be one month or more", ExceptionCode.REPAYMENT_TERM_EQUALS_TO_0); } try { var repaymentMonths = (payment.TermYears * 12) + payment.TermMonths; double rate = payment.AnnualInterestRate / 100 / 12; double denaminator = Math.Pow((1 + rate), repaymentMonths) - 1; return(Math.Round((rate + (rate / denaminator)) * payment.LoanAmount, 2, MidpointRounding.AwayFromZero)); } catch (Exception e) { throw new RepaymantCalculationException(e.Message, ExceptionCode.UN_HANDLED); } }
public void RepaymantServieTestCase1() { /* Loan amount = 145000 * Annual Interest rate = 4.5 (note this is the annual interest rate and we require a monthly repayment figure) * Term years = 23 * Term months = 7 * The resulting monthly repayment = 832.33 * Total to be repaid = 235549.39 */ Repayment paymentTest = new Repayment() { AnnualInterestRate = 4.5, LoanAmount = 145000, TermMonths = 7, TermYears = 23 }; var monthlyPaymant = paymentService.MonthlyPaymentAmount(paymentTest); var totalToBePaid = paymentService.AmountPaidBack(paymentTest); Assert.That(monthlyPaymant, Is.EqualTo(832.33)); Assert.That(totalToBePaid, Is.EqualTo(235549.39)); }
/// <summary> /// 还币 /// </summary> /// <param name="borrow_id">借币记录ID</param> /// <param name="instrument_id">杠杆币对名称</param> /// <param name="currency">币种</param> /// <param name="amount">借币数量</param> /// <returns></returns> public async Task <JObject> makeRepaymentAsync(long borrow_id, string instrument_id, string currency, string amount) { var url = $"{this.BASEURL}{this.MARGIN_SEGMENT}/accounts/repayment"; var body = new Repayment() { borrow_id = borrow_id, instrument_id = instrument_id, currency = currency, amount = amount }; var bodyStr = JsonConvert.SerializeObject(body); using (var client = new HttpClient(new HttpInterceptor(this._apiKey, this._secret, this._passPhrase, bodyStr))) { var res = await client.PostAsync(url, new StringContent(bodyStr, Encoding.UTF8, "application/json")); var contentStr = await res.Content.ReadAsStringAsync(); return(JObject.Parse(contentStr)); } }
public RepaymantViewModel getRepaymentData(RepaymantViewModel model) { try { // We can use Automapper to Map View Model to Model var paymant = new Repayment() { LoanAmount = model.LoanAmount, AnnualInterestRate = model.AnnualInterestRate, TermYears = model.TermYears, TermMonths = model.TermMonths }; model.MonthlyRepaymant = paymentService.MonthlyPaymentAmount(paymant); model.TotalToBePaid = paymentService.AmountPaidBack(paymant); return(model); } catch (Exception e) { throw new HttpResponseException(Request.CreateResponse( HttpStatusCode.NotAcceptable, new ErrorResponseView(e).message)); } }
public void RepaymantServieTestCase2() { /* * Given the following inputs: * Loan amount = 290000 * Annual Interest rate = 7.5 (note this is the annual interest rate and we require a monthly repayment figure) * Term years = 15 * Term months = 6 * The resulting monthly repayment = 2641.50 * Total to be repaid = 491319.00 */ Repayment paymentTest = new Repayment() { AnnualInterestRate = 7.5, LoanAmount = 290000, TermMonths = 6, TermYears = 15 }; var monthlyPaymant = paymentService.MonthlyPaymentAmount(paymentTest); var totalToBePaid = paymentService.AmountPaidBack(paymentTest); Assert.That(monthlyPaymant, Is.EqualTo(2641.50)); Assert.That(totalToBePaid, Is.EqualTo(491319.00)); }
/// <summary> /// Добавление списка графика платежей /// </summary> /// <param name="credits"></param> private void AddRepaymentItem(Credits credits) { int idcount = RepaymentId(); if (credits != null) { for (int i = 0; i < credits.MonthsPeriod; i++) { DateTime date = credits.OpenDate.AddMonths(i + 1); Repayment repayment = new Repayment() { Id = idcount, CreditId = credits.Id, RepaymentDate = date, PlanningDate = date, Performed = false, Amount = credits.MonthlyPayment }; RepaymentsList.Add(repayment); repayment.AddRepayment(); idcount += 1; } } }
private static async Task ApplyForLoanAsync(string phoneNumber) { Title("Apply for loan"); const double loanPercent = 0.03; var login = Ui.InputText("Search", 20, 3, 3, 1); Shred(); var users = await User.GetUsersWithProfileAsync(phoneNumber, login); var usersString = new List <string>(); users.ForEach(user => usersString.Add($"{user} ")); usersString.Add("Go back "); Shred(); Console.SetCursorPosition(2, 2); var index = Ui.ComboBox(usersString); if (index == usersString.Count - 1) { return; } var credit = new Credit(); Shred(); if (!double.TryParse(Ui.InputText("Total income:", 20, 3, 3, 1), out var totalIncome) && totalIncome < 10) { Shred(); Ui.Notification("invalid income value"); return; } Shred(); if (!int.TryParse(Ui.InputText("Number of closed credits:", 20, 3, 3, 1), out var numberOfClosedCredits) && numberOfClosedCredits < 0) { Shred(); Ui.Notification("invalid value for number of closed credits"); return; } Shred(); if (!int.TryParse(Ui.InputText("Number of delayed credits:", 20, 3, 3, 1), out var numberOfDelayedCredits) && numberOfDelayedCredits < 0) { Shred(); Ui.Notification("invalid value for number of delayed credits"); return; } Shred(); if (!int.TryParse(Ui.InputText("Loan terms:", 20, 3, 3, 1), out var loanTerms) && loanTerms < 1) { Shred(); Ui.Notification("invalid value for loan terms"); return; } Shred(); if (!int.TryParse(Ui.InputText("Loan amount:", 20, 3, 3, 1), out var loanAmount) && loanAmount < 1) { Shred(); Ui.Notification("invalid value for loan amount"); return; } Shred(); var purposes = new List <string> { "Appliances ", "Repair ", "Telephone ", "Other ", }; Console.SetCursorPosition(4, 1); Console.Write("Loan purpose:"); Console.SetCursorPosition(3, 2); credit.Purpose = (Credit.Purposes)(Ui.ComboBox(purposes) + 1); credit.TotalIncome = totalIncome; credit.History = numberOfClosedCredits; credit.Delinquencies = numberOfDelayedCredits; credit.Term = loanTerms; credit.LoanAmount = loanAmount; var points = CalculatePoints(users, index, credit); credit.Accepted = points > 11; credit.LoanAmount += credit.LoanAmount * loanPercent; credit.Id = await Credit.InsertCreditAsync(users[index].Id, credit); if (credit.Id == 0) { Shred(); Ui.Notification("unable to add new credit"); return; } if (!credit.Accepted) { Shred(); Ui.Notification("We are sorry but your application was not accepted", Ui.NotificationType.Warning); return; } var repayments = new List <Repayment>(); var amount = credit.LoanAmount / credit.Term; var currentTime = DateTime.Now; for (var i = 1; i <= credit.Term; i++) { currentTime = currentTime.AddMonths(1); var repayment = new Repayment { Amount = amount, RepaymentDate = currentTime, Repaid = false, }; repayments.Add(repayment); } if (await Repayment.InsertRepaymentAsync(credit.Id, repayments) < 1) { Shred(); Ui.Notification("unable to add repayments"); return; } var repaymentsList = new List <string>(); repayments.ForEach(item => repaymentsList.Add($"{item} ")); repaymentsList.Add("Back to main "); Console.SetCursorPosition(3, 2); var selectedIndex = 0; while (true) { Shred(); selectedIndex = Ui.ComboBox(repaymentsList, selectedIndex); if (selectedIndex == repaymentsList.Count - 1) { break; } } Shred(); Ui.Notification("Application accepted", Ui.NotificationType.Success); }
public PaymentViewModel(Repayment payment) { this.Id = payment.Id; this.PaidAt = payment.DueDate; }
protected void InsertButton_Click(object sender, EventArgs e) { Utils.IsAuthorized("LoanRepayment", "Create"); using (FinanceManagerDataContext db = new FinanceManagerDataContext()) { //check if investment has any contributions that can be used as loan payment //update investment Investment _investment; Loan _loan = db.Loans.FirstOrDefault(l => l.LoanID == Convert.ToInt32(Request.QueryString["lid"])); // int _investmentID ; //if (Request.QueryString["invID"] == null || Request.QueryString["invID"] == "") if (InvestmentID != null && InvestmentID > 0) { // _investmentID = Convert.ToInt32(Request.QueryString["invID"]); _investment = Utils.GetDataContext().Investments.FirstOrDefault(i => i.InvestmentID == InvestmentID); //total contributions towards the selected investment decimal? totalContributions = _investment.Contributions.Sum(c => c.ContributionAmount.Value); if (totalContributions != null) { if (totalContributions < Convert.ToDecimal(RepaymentAmountTextBox.Text)) { ErrorLabel.Text = "Repayment amount cannot be greater than the selected investment amount."; ErrorLabel.Visible = true; return; } else { //update investment withdrawal MemberWithdrawal _memberWithdrawal = new MemberWithdrawal() { CreatedBy = HttpContext.Current.User.Identity.Name, DateCreated = DateTime.Now, IsDeleted = false, InvestmentID = InvestmentID, Narration = "Payment For Loan", WithdrawalAmount = Convert.ToDecimal(RepaymentAmountTextBox.Text), WithdrawalIssuedByUserName = User.Identity.Name, WithdrawnBy = PaidTextBox.Text //, // groupi = Convert.ToInt32(Request.QueryString["gid"]) }; db.MemberWithdrawals.InsertOnSubmit(_memberWithdrawal); db.SubmitChanges(); //audit Utils.logAction("Insert", _memberWithdrawal); } } else //contributions { ErrorLabel.Text = "Repayment amount cannot be greater than the selected investment amount."; ErrorLabel.Visible = true; return; } } //set discription for repayment; payment by cash or with investment. string _description = Request.QueryString["invID"] == null || Request.QueryString["invID"] == "" ? "Loan repayment by cash" : "Loan repayment with investment"; int? _repaidWithInvestmentID = InvestmentID; if (InvestmentID == 0) _repaidWithInvestmentID = null; decimal _repaymentAmount = Convert.ToDecimal(RepaymentAmountTextBox.Text); decimal _interestRepayment = (_loan.Interest.Value / 100) * _repaymentAmount; Repayment _loanRepayment = new Repayment() { LoanId = Convert.ToInt32(Request.QueryString["lid"]), Description = _description, RepaymentAmount = _repaymentAmount, RepaymentBy = PaidTextBox.Text, // CreatedDate = DateTime.Now, CreatedBy = User.Identity.Name, RepaidWithInvestmentID = _repaidWithInvestmentID, InterestPayment = _interestRepayment, PrincipalPayment = _repaymentAmount - _interestRepayment, isDeleted = false, CreatedDate = DateWebUserControl1.DtSelectedDate }; //set current receipt number Parameter prm = db.Parameters.FirstOrDefault(); //set vale for receipt number if its zero if (prm.ReceiptNumber == null) prm.ReceiptNumber = 0; prm.ReceiptNumber++; //pad current receipt number with zeros _loanRepayment.ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'); //set repayment amount in wores value _loanRepayment.RepaymentAmountInWords = Utils.ConvertMoneyToText(_loanRepayment.RepaymentAmount.ToString()); db.Repayments.InsertOnSubmit(_loanRepayment); //update the selected schedule date if (ScheduleIDHiddenField.Value != "") { RepaymentSchedule _repaymentSchedule = db.RepaymentSchedules.FirstOrDefault(r => r.RepaymentScheduleId == Convert.ToInt32(ScheduleIDHiddenField.Value)); if (_repaymentSchedule != null) _repaymentSchedule.IsPaymentMade = true; } //submit changes to the database db.SubmitChanges(); //audit Utils.logAction("Insert", _loanRepayment); //rebind the repayment history data GridView1.DataBind(); //update the total repayment date in the UI GetLoanBalance(); //rebind loan schedules dropdown var loanSchedules = Utils.GetDataContext().RepaymentSchedules.Where(l => l.LoanId == Convert.ToInt32(Request.QueryString["lid"]) && Convert.ToBoolean(l.IsPaymentMade) == false).OrderBy(r => r.RepaymentDate); FriendGridView.DataSource = loanSchedules; FriendGridView.DataBind(); //clear controls PaidTextBox.Text = ""; txtFriend.Text = ""; RepaymentAmountTextBox.Text = ""; // ScriptManager.RegisterStartupScript(this, GetType(), "Receipt", "openWindow('RepaymentReceipt.aspx?rid='" + _loanRepayment.RepaymentId.ToString() + "&mid=" + _loanRepayment.Loan.MemberId + "');", true); //Response.Write("<SCRIPT language=javascript>var w=window.open('RepaymentReceipt.aspx?rid=' + _loanRepayment.RepaymentId.ToString() + '&mid=' + _loanRepayment.Loan.MemberId','OrderStatus','height=800,width=800');</SCRIPT>"); Response.Redirect("RepaymentReceipt_Group.aspx?rid=" + _loanRepayment.RepaymentId.ToString() + "&gid=" + _loanRepayment.Loan.GroupID); } }
public Repayment UpdateRepayment(Repayment repayment) => Update(repayment);
public Repayment AddRepayment(Repayment repayment) => Add(repayment);