protected void btnSave_Click(object sender, EventArgs e) { using (FinanceManagerDataContext db = new FinanceManagerDataContext()) { LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault(); double InvsetmentAmount = double.Parse(PrincipalTextBox.Text); double MaturedInvestmentAmount;// = double.Parse(lblTotalAmount.Text); // double interestRate = Convert.ToDouble(InterestTextBox.Text); //Convert.ToDouble(cProfile.CompoundInterestRate.Value); LoanDuration _loanDuration = db.LoanDurations.FirstOrDefault(l => l.LoanDurationId == Convert.ToInt32(cboLoanDurationType.SelectedValue)); if (_loanDuration == null) return; //int period = int.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value; decimal period = decimal.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value / 12; //LoanPreset _loanPreset = db.LoanPresets.First(l => l.LoanPresetId == Convert.ToInt32(cboInterestDuration.SelectedValue)); //double interestRate = Utils.CalculateInterestRateByDuration(_loanPreset.InsterestRate.Value, period); //double interestRate = Utils.CalculateInterestRateByDuration(decimal.Parse(InterestTextBox.Text), period); double interestRate = double.Parse(InterestTextBox.Text); // int period = int.Parse(DurationTextBox.Text); int compoundType = cProfile.CompoundFrequency.Value; //using repayment frequency for contribution frequency //RepaymentFrequency _repaymentFrequency = db.RepaymentFrequencies.FirstOrDefault(r => r.RepaymentFrequencyId == int.Parse(RepaymentFrequencyDropdownList.SelectedValue)); double amount; if (InterestTypeDropDownList.SelectedValue == "1") //compound { amount = Utils.calculateCompoundInterest(InvsetmentAmount, interestRate, period, Utils.GetCompoundType(compoundType)); } else //2 for simple interest { amount = Utils.calculateSimpleInterest(InvsetmentAmount, interestRate, period); } decimal _originalInvestmentAmount = 0; //get an existing investment or create a new one Investment newInvestment; if (Request.QueryString["InvId"] != null) { newInvestment = db.Investments.FirstOrDefault(i => i.InvestmentID == Convert.ToInt32(Request.QueryString["InvId"])); _originalInvestmentAmount = newInvestment.InvestmentAmount.Value; } else { newInvestment = new Investment(); } //set invementType to 3 for fixed deposit investment newInvestment.InvestmentTypeId = 3; //newLoan.ActualRepaymentEndDate = DateTime.Today.AddMonths(period); // newLoan.Amount = (decimal)amount; if (Request.QueryString["mid"] != null) { newInvestment.MemberID = Convert.ToInt32(Request.QueryString["mid"]); } else { newInvestment.GroupId = Convert.ToInt32(Request.QueryString["gid"]); } newInvestment.IsDeleted = false; newInvestment.InvestmentAmount = (decimal)InvsetmentAmount; //newInvestment.ContributionFrequencyId = _repaymentFrequency.RepaymentFrequencyId; newInvestment.IsMatured = false; newInvestment.InsterstRate = (decimal)interestRate; newInvestment.Duration = decimal.Parse(DurationTextBox.Text); newInvestment.InterestTypeId = Convert.ToInt32(InterestTypeDropDownList.SelectedValue); //newLoan.payWithContribution = false; newInvestment.InvestmentCalculationStartDate = DateWebUserControl1.DtSelectedDate; newInvestment.IsActive = true; newInvestment.InterestDurationTypeID = Convert.ToInt32(cboLoanDurationType.SelectedValue); //variable to hold period for the calculation of MaturityDate calculation int tempPeriod; tempPeriod = int.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value; //start calculation from the LoanCalculationStartDate specified newInvestment.MaturityDate = newInvestment.InvestmentCalculationStartDate.Value.AddMonths(tempPeriod); //if the expected repayment end date falls on a weekend, move it to a working if (newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Saturday) { newInvestment.MaturityDate = newInvestment.MaturityDate.Value.AddDays(2); } else if (newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Sunday) { newInvestment.MaturityDate = newInvestment.MaturityDate.Value.AddDays(1); } newInvestment.DurationTypeId = Convert.ToInt32(cboLoanDurationType.SelectedValue); //newLoan.RawDurationEntered = DurationTextBox.Text; newInvestment.InvestmentCalculationStartDate = DateTime.Now; TimeSpan tSpan = newInvestment.MaturityDate.Value - newInvestment.InvestmentCalculationStartDate.Value;// -DateTime.Today; double numberOfDaysBetweenExpectedEndDateAndNow = tSpan.TotalDays; //int xx = (int)numberOfDaysBetweenExpectedEndDateAndNow / _repaymentFrequency.NumberOfDays.Value; //int numberOfDaysBetweenExpectedEndDateAndNow = 30 * period; //assuming there are 30 days in a month //decimal xx = numberOfDaysBetweenExpectedEndDateAndNow / _repaymentFrequency.NumberOfDays.Value; //newInvestment.ContributionFreqAmount = ((decimal)newInvestment.InvestmentAmount / xx); //maturity amount MaturedInvestmentAmount = amount; newInvestment.CreatedBy = this.User.Identity.Name; newInvestment.MaturedAmount = (decimal)amount; //set invementType to 3 for fixed deposit investment newInvestment.InvestmentTypeId = 3; Parameter prm = db.Parameters.FirstOrDefault(); //increase receipt number by one prm.ReceiptNumber++; if (Request.QueryString["InvId"] != null) { newInvestment.ModifiedDate = DateTime.Now; newInvestment.ModifiedBy = HttpContext.Current.User.Identity.Name; //audit Utils.logAction("Edit", newInvestment); db.SubmitChanges(); //make contibution if the original amount is less than the new amount otherwise make a withrawal if (newInvestment.InvestmentAmount > _originalInvestmentAmount) { //make contribution Contribution _contribution = new Contribution() { ContributionAmount = newInvestment.InvestmentAmount - _originalInvestmentAmount, ContributionBy = "Self", ContributionAmountInWords = Utils.ConvertMoneyToText(newInvestment.InvestmentAmount.ToString()), Description = "Fixed deposit contribution as a result of a edit action on an the investment", ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'), RecievedBy = User.Identity.Name, InvestmentId = newInvestment.InvestmentID, PaymentMethodId = PaymentMethodWebUserControl1.PaymentTypeID, ChequeNumber = PaymentMethodWebUserControl1.ChequeNumber, IsDeleted = false, CreatedDate = DateWebUserControl1.DtSelectedDate, CreatedBy = HttpContext.Current.User.Identity.Name }; _contribution.CreatedDate = DateWebUserControl1.DtSelectedDate; db.Contributions.InsertOnSubmit(_contribution); db.SubmitChanges(); //audit Utils.logAction("Insert", _contribution); } else if (newInvestment.InvestmentAmount < _originalInvestmentAmount) { //make withdrawal MemberWithdrawal _memberWithdrawal = new MemberWithdrawal() { CreatedBy = HttpContext.Current.User.Identity.Name, DateCreated = DateTime.Now, IsDeleted = false, WithdrawalAmount = _originalInvestmentAmount - newInvestment.InvestmentAmount , WithdrawnBy = "Self", //ContributionAmountInWords = Utils.ConvertMoneyToText(newInvestment.InvestmentAmount.ToString()), Narration = "Fixed deposit withdrawal as a result of a edit action on an the investment", //ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'), WithdrawalIssuedByUserName = User.Identity.Name, InvestmentID = newInvestment.InvestmentID }; db.MemberWithdrawals.InsertOnSubmit(_memberWithdrawal); db.SubmitChanges(); //audit Utils.logAction("Insert", _memberWithdrawal); } } else { newInvestment.CreatedDate = DateTime.Now; db.Investments.InsertOnSubmit(newInvestment); db.SubmitChanges(); //audit Utils.logAction("Insert", newInvestment); //make initial contribution if fixed deposit investment is a new one //add contribution since it a fixed deposit Contribution _contribution = new Contribution() { ContributionAmount = newInvestment.InvestmentAmount, ContributionBy = "Self", ContributionAmountInWords = Utils.ConvertMoneyToText(newInvestment.InvestmentAmount.ToString()), Description = "Fixed deposit contribution", ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'), RecievedBy = User.Identity.Name, InvestmentId = newInvestment.InvestmentID, IsDeleted = false, CreatedDate = DateWebUserControl1.DtSelectedDate, CreatedBy = HttpContext.Current.User.Identity.Name }; db.Contributions.InsertOnSubmit(_contribution); db.SubmitChanges(); //audit Utils.logAction("Insert", _contribution); } //ResponseHelper.Redirect(this.Response, "ContributionReceipt.aspx?cid=" + _contribution.ContributionId.ToString() + "&mid=" + _contribution.Investment.MemberID, "_blank", "menubar=0,width=100,height=100"); if (Request.QueryString["mid"] != null) { Response.Redirect("FixedDepositInvestmentStatement.aspx?invID=" + newInvestment.InvestmentID + "&mid=" + Request.QueryString["mid"]); } else if(Request.QueryString["gid"] != null) { Response.Redirect("FixedDepositInvestmentStatement.aspx?invID=" + newInvestment.InvestmentID + "&gid=" + Request.QueryString["gid"]); } } }
protected void Button1_Click(object sender, EventArgs e) { //withdraw all money using (FinanceManagerDataContext db = new FinanceManagerDataContext()) { MemberWithdrawal _memberWithdrawal = new MemberWithdrawal() { CreatedBy = HttpContext.Current.User.Identity.Name, DateCreated = DateTime.Now, IsDeleted = false, InvestmentID = Convert.ToInt32( InvestmentIDHiddenField.Value), Narration = "Withdrawal For Rollover", WithdrawalIssuedByUserName = HttpContext.Current.User.Identity.Name, WithdrawnBy = "System", WithdrawalAmount = Convert.ToDecimal( txtFriend.Text) }; //submit withdrawal changes db.MemberWithdrawals.InsertOnSubmit(_memberWithdrawal); //update the status of the current investment Investment _currentinvestment = db.Investments.FirstOrDefault(i => i.InvestmentID == Convert.ToInt32(InvestmentIDHiddenField.Value)); _currentinvestment.IsActive = false; //get company profile LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault(); //get compound type -- thus, annully, monthly, weekly etc int compoundType = cProfile.CompoundFrequency.Value; LoanDuration _loanDuration = db.LoanDurations.FirstOrDefault(l => l.LoanDurationId == _currentinvestment.DurationTypeId.Value);//Convert.ToInt32(cboLoanDurationType.SelectedValue)); if (_loanDuration == null) return; //calculate matured amount for the new investment double _maturedAmountForNewInvestment; DateTime _maturityDate = DateTime.Now; decimal period = _currentinvestment.Duration.Value * _loanDuration.NumberOfMonths.Value / 12; if (_currentinvestment.InterestTypeId.Value == 1) //compound { _maturedAmountForNewInvestment = Utils.calculateCompoundInterest(Convert.ToDouble(_currentinvestment.MaturedAmount.Value), Convert.ToDouble(_currentinvestment.InsterstRate.Value), period, Utils.GetCompoundType(compoundType)); } else //2 for simple interest { _maturedAmountForNewInvestment = Utils.calculateSimpleInterest(Convert.ToDouble(_currentinvestment.MaturedAmount.Value), Convert.ToDouble(_currentinvestment.InsterstRate.Value), period); } //create new investment Investment _newInvestment = new Investment() { IsActive = true, InvestmentTypeId = _currentinvestment.InvestmentTypeId, IsMatured = false, //ContributionFreqAmount = _currentinvestment.ContributionFreqAmount, //not calculating ContributionFreqAmount because after an investment is rolled over it becomes a fixed deposit Duration = _currentinvestment.Duration, DurationTypeId = _currentinvestment.DurationTypeId, GroupId = RadioButtonList1.SelectedIndex == 1 ? _currentinvestment.GroupId : null, InterestTypeId = _currentinvestment.InterestTypeId, InvestmentAmount = _currentinvestment.MaturedAmount, MaturedAmount = (decimal)_maturedAmountForNewInvestment, InvestmentCalculationStartDate = DateTime.Today, MaturityDate = _maturityDate, MemberID = RadioButtonList1.SelectedIndex == 0 ? _currentinvestment.MemberID : null, ParentInvestmentID = _currentinvestment.InvestmentID, InsterstRate = _currentinvestment.InsterstRate }; //calculate maturity date //variable to hold period for the calculation of MaturityDate calculation int tempPeriod; tempPeriod = Convert.ToInt32(_currentinvestment.Duration.Value) * _loanDuration.NumberOfMonths.Value; //start calculation from the LoanCalculationStartDate specified _newInvestment.MaturityDate = _newInvestment.InvestmentCalculationStartDate.Value.AddMonths(tempPeriod); //if the expected repayment end date falls on a weekend, move it to a working if (_newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Saturday) { _newInvestment.MaturityDate = _newInvestment.MaturityDate.Value.AddDays(2); } else if (_newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Sunday) { _newInvestment.MaturityDate = _newInvestment.MaturityDate.Value.AddDays(1); } db.Investments.InsertOnSubmit(_newInvestment); db.SubmitChanges(); //audit Utils.logAction("Insert", _newInvestment); Utils.logAction("Insert", _memberWithdrawal); //set current receipt number Parameter prm = db.Parameters.FirstOrDefault(); //increase receipt number by one prm.ReceiptNumber++; Contribution _newDeposit = new Contribution() { ContributionAmount = _currentinvestment.MaturedAmount, InvestmentId = _currentinvestment.InvestmentID, ContributionAmountInWords = Utils.ConvertMoneyToText(_currentinvestment.MaturedAmount.ToString()), ContributionBy = "System", Description = "Rollover from Investment: " + _currentinvestment.InvestmentID.ToString(), ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'), RecievedBy = User.Identity.Name }; Response.Redirect(DropDownList1.SelectedIndex > 0 ? "MemberInvestments.aspx?mid=" + DropDownList1.SelectedValue : "GroupInvestments.aspx?gid=" + cboGroupName.SelectedValue); } }
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); } }