示例#1
0
        private void LoanHistory_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            LoanHistory loanHistory = new LoanHistory();

            loanHistory.Show();
            Hide();
        }
        public ActionResult EditPayment(LoanHistory collection)
        {
            ViewBag.Action = "Edit Payment";
            using (LinkToDBDataContext context = new LinkToDBDataContext())
            {
                LoanHistory history = context.GetLoanHistoryItem(collection.Id);
                try
                {
                    history.ModifyDate    = DateTime.Now;
                    history.Version      += 1;
                    history.DatePaid      = collection.DatePaid;
                    history.BasicPayment  = collection.BasicPayment;
                    history.AddPayment    = collection.AddPayment;
                    history.Interest      = collection.Interest;
                    history.Escrow        = collection.Escrow;
                    history.PaymentTypeId = collection.PaymentTypeId;

                    context.SubmitChanges();

                    return(RedirectToAction("View", new { id = history.LoanId }));
                }
                catch
                {
                    return(View("Payment", collection));
                }
            }
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,LondDate,LondDateTime,CreationDate,ClientId,VideoGameId")] LoanHistory loanHistory)
        {
            if (id != loanHistory.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(loanHistory);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!LoanHistoryExists(loanHistory.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ClientId"]    = new SelectList(_context.Client, "Id", "Id", loanHistory.ClientId);
            ViewData["VideoGameId"] = new SelectList(_context.VideoGame, "Id", "Id", loanHistory.VideoGameId);
            return(View(loanHistory));
        }
        public async Task <LoanHistory> AddLoanHistoryAsync(LoanHistory LoanHistory)
        {
            var result = await _magContext.loanHistories.AddAsync(LoanHistory);

            await _magContext.SaveChangesAsync();

            return(result.Entity);
        }
示例#5
0
 public string SaveHistory(LoanHistory history)
 {
     using (LoanPriceEntities context = new LoanPriceEntities())
     {
         context.AddToLoanHistories(history);
         context.SaveChanges();
         return("History is added successfully");
     }
 }
示例#6
0
        public ActionResult Create([Bind(Include = "ClientAccountId,StartAmount,StartDate,FreeDays,InterestRate, Notes")] Loan loan)
        {
            if (ModelState.IsValid)
            {
                DateTime time = DateTime.Now;
                loan.Timestamp     = time;
                loan.EndDate       = null;
                loan.CurrentAmount = loan.StartAmount;

                db.Loans.Add(loan);

                var client = db.ClientAccounts.Find(loan.ClientAccountId);

                if (client.Loan + loan.StartAmount > client.LoanLimit)
                {
                    throw new InvalidOperationException("超出贷款上限");
                }

                client.Loan += loan.StartAmount;

                db.Entry(client).State = EntityState.Modified;

                db.SaveChanges();

                client.Balance += loan.StartAmount;

                var clientBalanceHistory = new ClientBalanceHistory()
                {
                    Amount          = loan.StartAmount,
                    BalanceType     = BalanceChangeType.Loan,
                    ClientAccountId = client.ClientAccountId,
                    Description     = string.Format("Loan for LoanId: {0}.", loan.LoanId),
                    Timestamp       = time
                };

                db.ClientBalanceHistories.Add(clientBalanceHistory);

                var loanHistory = new LoanHistory()
                {
                    Amount     = loan.StartAmount,
                    DealDate   = loan.StartDate,
                    ChangeType = LoanChangeType.Loan,
                    Interest   = 0,
                    LoanId     = loan.LoanId,
                    Notes      = loan.Notes,
                    Timestamp  = time
                };

                db.LoanHistories.Add(loanHistory);
                db.SaveChanges();

                return(RedirectToAction("Index", new { accountId = loan.ClientAccountId }));
            }

            return(View(loan));
        }
 public ActionResult EditPayment(int id)
 {
     ViewBag.Action = "Edit Payment";
     using (LinkToDBDataContext context = new LinkToDBDataContext())
     {
         LoanHistory history = context.GetLoanHistoryItem(id);
         history.Loan = context.GetLoan(history.LoanId);
         return(View("Payment", history));
     }
 }
示例#8
0
        public void simple_report()
        {
            var date  = new DateTime(2012, 10, 10);
            var loan1 = new Loan()
            {
                Date = date.AddDays(-10), Balance = 100, Interest = 10
            };

            loan1.Customer = new Customer()
            {
                PersonalInfo = new PersonalInfo()
                {
                    Fullname = "Test Test Test"
                }
            };

            var installment1 = new LoanScheduleItem()
            {
                Loan = loan1, Date = date.AddDays(-9), AmountDue = 50, Balance = 50, Interest = 1
            };

            var lh1 = new LoanHistory(loan1, date.AddDays(-10))
            {
                Loan = loan1
            };
            var lh2 = new LoanHistory(loan1, date.AddDays(-9))
            {
                Loan = loan1, Balance = 51
            };
            var tran1 = new PaypointTransaction()
            {
                Amount = 50, Interest = 1, Balance = 49, Loan = loan1, Fees = 0, PostDate = date.AddDays(-9)
            };

            using (var tx = _session.BeginTransaction())
            {
                _session.Save(loan1);
                _session.Save(installment1);
                _session.Save(lh1);
                _session.Save(lh2);
                _session.Save(tran1);
                tx.Commit();
            }

            var builder = new DailyReportBuilder(_loanScheduleRepository, _transactions, _historyRepository);
            var report  = builder.GenerateReport(2012, 10, 1);

            Assert.That(report.Count, Is.EqualTo(1));
            Assert.That(report[0].Before.Balance, Is.EqualTo(100));
            Assert.That(report[0].After.Balance, Is.EqualTo(51));
            Assert.That(report[0].Paid.Balance, Is.EqualTo(49));
        }
        public void can_save_loan_history_item()
        {
            var lh = new LoanHistory {
                Balance = 99.98M, Date = DateTime.Now, Interest = 0.5M, Principal = 99.48M, Loan = _loan
            };

            _lhrepo.Save(lh);

            var historyItems = _lhrepo.GetByLoan(_loan).ToList();

            Assert.That(historyItems.Count, Is.EqualTo(1));
            Assert.That(historyItems[0].Balance, Is.EqualTo(99.98M));
        }
        public async Task <IActionResult> Create([Bind("Id,LondDate,LondDateTime,CreationDate,ClientId,VideoGameId")] LoanHistory loanHistory)
        {
            if (ModelState.IsValid)
            {
                _context.Add(loanHistory);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ClientId"]    = new SelectList(_context.Client, "Id", "Id", loanHistory.ClientId);
            ViewData["VideoGameId"] = new SelectList(_context.VideoGame, "Id", "Id", loanHistory.VideoGameId);
            return(View(loanHistory));
        }
示例#11
0
		} // ToString

		/// <summary>
		/// Creates a deep copy of current model.
		/// </summary>
		/// <returns>A copy of current model.</returns>
		public LoanCalculatorModel DeepClone() {
			var lcm = new LoanCalculatorModel {
				InterestOnlyRepayments = InterestOnlyRepayments,
			};

			lcm.DiscountPlan.AddRange(DiscountPlan);
			lcm.Repayments.AddRange(Repayments.Select(v => v.DeepClone()));
			lcm.Fees.AddRange(Fees.Select(v => v.DeepClone()));
			lcm.BadPeriods.AddRange(BadPeriods.Select(v => v.DeepClone()));

			lcm.LoanHistory.Clear();
			lcm.LoanHistory.AddRange(LoanHistory.Select(v => v.DeepClone()));

			return lcm;
		} // DeepClone
        public void paying_early_save_new_loan_to_history()
        {
            LoanHistory copy = null;

            _historyRepoMock.Setup(x => x.Save(It.IsAny <LoanHistory>())).Callback <LoanHistory>(lh =>
            {
                copy = lh;
            });

            _facade.MakePayment("transaction", 1000, "", "loan", _loan.Id, _customer, _startDate);

            _historyRepoMock.Verify(x => x.Save(It.IsAny <LoanHistory>()), Times.Exactly(1));

            Assert.That(copy.Balance, Is.EqualTo(_loan.Balance));
            Assert.That(copy.Interest, Is.EqualTo(_loan.Interest));
            Assert.That(copy.Principal, Is.EqualTo(_loan.Principal));
        }
示例#13
0
        public async Task <LoanHistory> UpdateLoanHistoryAsync(LoanHistory LoanHistory)
        {
            var result = await _magContext.loanHistories
                         .FirstOrDefaultAsync(m => m.Id == LoanHistory.Id);

            if (result != null)
            {
                result.Id            = LoanHistory.Id;
                result.ItemId        = LoanHistory.ItemId;
                result.LastOwnerId   = LoanHistory.LastOwnerId;
                result.ActualOwnerId = LoanHistory.ActualOwnerId;

                await _magContext.SaveChangesAsync();

                return(result);
            }
            return(null);
        }
        public void LoanOut(int id, string ssn)
        {
            if (IsLoanedOut(id))
            {
                return;
            }

            var book = _context.BookDetails
                       .Include(a => a.Status)
                       .First(a => a.ID == id);

            _context.Update(book);

            book.Status = _context.Statuses
                          .FirstOrDefault(a => a.Name == "Loaned Out");

            var now = DateTime.Now;

            var member = _context.Members
                         .Include(x => x.BorrowedBooks)
                         .FirstOrDefault(a => a.SSN == ssn);

            var loan = new Loan
            {
                BorrowedBook    = book,
                BorrowingMember = member,
                StartLoan       = now,
                EndLoan         = GetDefaultLoanTime(now)
            };

            _context.Add(loan);

            var loanHistory = new LoanHistory
            {
                LoanedOut   = now,
                BookDetails = book,
                Member      = member
            };

            _context.Add(loanHistory);
            _context.SaveChanges();
        }
示例#15
0
		} // ActualIssuedAmount

		public void ValidateSchedule() {
			if (LoanHistory.Count < 1)
				throw new NoScheduleException();

			LoanHistory last = null;

			foreach (LoanHistory lh in LoanHistory) {
				lh.ValidateSchedule();

				if (last == null) {
					last = lh;
					continue;
				} // if

				if (last.Time >= lh.Time)
					throw new WrongLoanHistoryOrderException(last, lh);

				last = lh;
			} // for each
		} // ValidateSchedule
示例#16
0
        public void fetches_most_rescent_history_by_loan()
        {
            var date = DateTime.Now;

            //loan ititial state
            var i1 = new LoanHistory()
            {
                Balance = 100, Loan = _loan, Date = date.AddDays(-10)
            };

            //partial payment fees
            var i2 = new LoanHistory()
            {
                Balance = 90, Loan = _loan, Date = date.AddDays(-8).AddHours(2), ExpectedAmountDue = 50, ExpectedFees = 10, ExpectedInterest = 10, ExpectedPrincipal = 30
            };

            //partial payment balance
            var i3 = new LoanHistory()
            {
                Balance = 50, Loan = _loan, Date = date.AddDays(-8).AddHours(4), ExpectedAmountDue = 40, ExpectedFees = 0, ExpectedInterest = 10, ExpectedPrincipal = 30
            };

            //early payment
            var i4 = new LoanHistory()
            {
                Balance = 0, Loan = _loan, Date = date.AddDays(0).AddHours(2)
            };

            _lhrepo.Save(i1);
            _lhrepo.Save(i2);
            _lhrepo.Save(i3);
            _lhrepo.Save(i4);

            var h = _lhrepo.FetchHistoryByDay(_loan, date.AddDays(-8));

            Assert.That(h.Before.Balance, Is.EqualTo(100));
            Assert.That(h.Expected.ExpectedAmountDue, Is.EqualTo(50));
            Assert.That(h.After.Balance, Is.EqualTo(50));
        }
示例#17
0
        public ActionResult RepayConfirmed([Bind(Include = "LoanId,RepayDate, RepayAmount, Notes")] LoanRepayViewModel loanRepayViewModel)
        {
            DateTime time = DateTime.Now;

            if (ModelState.IsValid)
            {
                var loan = db.Loans.Find(loanRepayViewModel.LoanId);

                if (loan == null)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }

                double totalRepayAmount = GetRepayAmountWithInterest(
                    loanRepayViewModel.RepayAmount,
                    loan.InterestRate,
                    loan.StartDate,
                    loanRepayViewModel.RepayDate,
                    loan.FreeDays);

                var client = db.ClientAccounts.Find(loan.ClientAccountId);

                if (client == null)
                {
                    return(HttpNotFound());
                }

                if (client.Balance < totalRepayAmount)
                {
                    return(View(string.Format("The balance is not enough to pay the loan with interest {0}.", totalRepayAmount)));
                }

                client.Loan           -= loanRepayViewModel.RepayAmount;
                client.Balance        -= totalRepayAmount;
                db.Entry(client).State = EntityState.Modified;

                var loanHistory = new LoanHistory()
                {
                    Amount     = loanRepayViewModel.RepayAmount * -1,
                    DealDate   = loanRepayViewModel.RepayDate,
                    Interest   = totalRepayAmount - loanRepayViewModel.RepayAmount,
                    ChangeType = LoanChangeType.Repay,
                    LoanId     = loan.LoanId,
                    Notes      = loan.Notes,
                    Timestamp  = time
                };

                db.LoanHistories.Add(loanHistory);

                loan.CurrentAmount -= loanRepayViewModel.RepayAmount;
                loan.Timestamp      = time;

                if (loan.CurrentAmount == 0)
                {
                    loan.EndDate = loanRepayViewModel.RepayDate;
                }

                db.Entry(loan).State = EntityState.Modified;

                var clientBalanceHistory = new ClientBalanceHistory()
                {
                    Amount          = totalRepayAmount * -1,
                    BalanceType     = BalanceChangeType.LoanRepay,
                    ClientAccountId = client.ClientAccountId,
                    Description     = string.Format("Repay for Loan: {0}.", loan.LoanId),
                    Timestamp       = time
                };

                db.ClientBalanceHistories.Add(clientBalanceHistory);

                try
                {
                    db.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    string errorMessage = "";

                    foreach (var result in e.EntityValidationErrors)
                    {
                        foreach (var error in result.ValidationErrors)
                        {
                            errorMessage += error.ErrorMessage;
                        }
                    }

                    throw new Exception(errorMessage);
                }
                return(RedirectToAction("Index", new { accountId = client.ClientAccountId }));
            }

            return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
        }
示例#18
0
        }         // constructor

        /// <summary>
        /// Заплатить за кредит. Платёж может быть произвольный. Early, On time, Late.
        /// Perform loan payment. Payment can be manual. Early, On time, Late.
        /// </summary>
        public virtual decimal PayLoan(
            Loan loan,
            string transId,
            decimal amount,
            string ip,
            DateTime?term               = null,
            string description          = "payment from customer",
            bool interestOnly           = false,
            string sManualPaymentMethod = null,
            NL_Payments nlPayment       = null)
        {
            int customerID = loan.Customer.Id;

            var paymentTime = term ?? DateTime.UtcNow;

            var oldLoan = loan.Clone();

            const string Manual      = "--- manual ---";
            string       otherMethod = transId == Manual ? "Manual" : "Auto";

            var loanTransactionMethod = this.loanTransactionMethodRepository.FindOrDefault(sManualPaymentMethod, otherMethod);
            var transaction           = this.session.BeginTransaction();

            var transactionItem = new PaypointTransaction {
                Amount                = amount,
                Description           = description,
                PostDate              = paymentTime,
                Status                = LoanTransactionStatus.Done,
                PaypointId            = transId,
                IP                    = ip,
                LoanRepayment         = oldLoan.Principal - loan.Principal,
                Interest              = loan.InterestPaid - oldLoan.InterestPaid,
                InterestOnly          = interestOnly,
                LoanTransactionMethod = loanTransactionMethod
            };

            try {
                loan.AddTransaction(transactionItem);

                List <InstallmentDelta> deltas = loan.Schedule.Select(inst => new InstallmentDelta(inst))
                                                 .ToList();

                var calculator = new LoanRepaymentScheduleCalculator(loan, paymentTime, this.amountToChargeFrom);
                calculator.RecalculateSchedule();

                if (this._historyRepository != null)
                {
                    var historyRecord = new LoanHistory(loan, paymentTime);
                    this._historyRepository.SaveOrUpdate(historyRecord);
                }                 // if

                loan.UpdateStatus(paymentTime);

                if (loan.Customer != null)
                {
                    loan.Customer.UpdateCreditResultStatus();
                }
                if (loan.Id > 0)
                {
                    foreach (InstallmentDelta dlt in deltas)
                    {
                        dlt.SetEndValues();

                        if (dlt.IsZero)
                        {
                            continue;
                        }

                        loan.ScheduleTransactions.Add(new LoanScheduleTransaction {
                            Date           = DateTime.UtcNow,
                            FeesDelta      = dlt.Fees.EndValue - dlt.Fees.StartValue,
                            InterestDelta  = dlt.Interest.EndValue - dlt.Interest.StartValue,
                            Loan           = loan,
                            PrincipalDelta = dlt.Principal.EndValue - dlt.Principal.StartValue,
                            Schedule       = dlt.Installment,
                            StatusAfter    = dlt.Status.EndValue,
                            StatusBefore   = dlt.Status.StartValue,
                            Transaction    = transactionItem
                        });
                    }             // for each delta
                }                 // if


                if (nlPayment != null)
                {
                    Log.InfoFormat("PayLoan: oldLoanID: {0} customer: {1} nlpayment {2}", loan.Id, customerID, nlPayment);

                    // override those for backword compatibility
                    nlPayment.PaymentMethodID = loanTransactionMethod.Id;
                    nlPayment.Notes           = description;
                    nlPayment.CreationTime    = DateTime.UtcNow;
                    nlPayment.PaymentTime     = paymentTime;
                    nlPayment.Amount          = amount;
                    nlPayment.PaymentStatusID = (int)NLPaymentStatuses.Active;

                    Log.InfoFormat("PayLoan: overriden nlpayment {0}", nlPayment);

                    long nlLoanId = serviceInstance.GetLoanByOldID(loan.Id, customerID);

                    if (nlLoanId == 0)
                    {
                        Log.InfoFormat("Failed to find nl loan for oldLoanID {0}, customer {1}", loan.Id, customerID);
                    }
                    else
                    {
                        nlPayment.LoanID = nlLoanId;

                        // use argument's nlPayment data: CreatedByUserID

                        if (nlPayment.PaymentSystemType == NLPaymentSystemTypes.Paypoint)
                        {
                            // workaround - from MakeAutomaticPayment sent transactionid with timestamp concated

                            var card = loan.Customer.PayPointCards.FirstOrDefault(x => transId.StartsWith(x.TransactionId));

                            if (card == null)
                            {
                                Log.InfoFormat("PayPointCard for customer {0}, transId={1}, oldLoanID={2}, nl loanID={3} not found. nl payment\n {4}{5}",
                                               customerID, transId, loan.Id, nlPayment.LoanID, AStringable.PrintHeadersLine(typeof(NL_Payments)), nlPayment.ToStringAsTable());
                            }
                            else
                            {
                                nlPayment.PaypointTransactions.Clear();
                                nlPayment.PaypointTransactions.Add(new NL_PaypointTransactions()
                                {
                                    TransactionTime             = paymentTime,
                                    Amount                      = amount,
                                    Notes                       = description,
                                    PaypointTransactionStatusID = (int)NLPaypointTransactionStatuses.Done,
                                    PaypointUniqueID            = transId,
                                    PaypointCardID              = card.Id,
                                    IP = ip
                                });
                            }
                        }

                        serviceInstance.AddPayment(customerID, nlPayment, nlPayment.CreatedByUserID);
                    }
                }

                transaction.Commit();
            } catch (Exception ex) {
                Log.ErrorFormat("Failed to pay {1} pounds for loan {0}, rollbacking \n {2}", loan.Id, amount, ex);
                transaction.Rollback();
            }

            Log.InfoFormat("LinkPaymentToInvestor {0} {1} {2} {3} {4} begin", transactionItem.Id, loan.Id, loan.Customer.Id, amount, paymentTime);
            serviceInstance.LinkPaymentToInvestor(1, transactionItem.Id, loan.Id, loan.Customer.Id, amount, paymentTime);             // modified by elinar at 9/02/2016 EZ-4678 bugfix

            return(amount);
        }         // PayLoan