public ActionResult Create(//[Bind(Include = "LoanId,UserId,RepaymentStartDate,RePaymentInterval,RequestedAmount,ProposedAmount,LoanAmount,TotalInstallments,Status,ChequeDetails,InteresRate,SanctionedDate,SanctionedBy,Notes,CreatedOn,ModifiedOn,CreatedBy,ModifiedBy,IsDeleted,DeletedBy,DeletedOn")] 
            sdtoLoanInfo LoanInfo)
        {
            if (ModelState.IsValid)
            {
                LoanInfo.InstallmentAmount = LoanInfo.LoanAmount / LoanInfo.TotalInstallments;
                LoanInfo.CreatedOn = DateTime.Now;
                bfReport objReport = new bfReport(db);

                LoanInfo.CreatedBy = CurrentUserSession.UserId;
                LoanInfo.LoanCode = objReport.GenerateCode("LoanInfo");
                db.sdtoLoanInfoes.Add(LoanInfo);
                db.SaveChanges();

                bfTransaction objTrans = new bfTransaction(db);
                objTrans.PostLoanIssue(LoanInfo);

                SetDisplayMessage("Loan is created successfully");

                return RedirectToAction("Index");
            }

            var listUsers = db.User.Where(x => x.UserType == UserType.Member && x.IsDeleted == false);
            var users = listUsers.Select(x => new SelectListItem() { Value = x.UserID.ToString(), Text = x.FirstName + " " + x.LastName }).ToList();
            users.Insert(0, new SelectListItem() { Value = "0", Text = "Select a Member" });
            ViewBag.UserList = new SelectList(users, "Value", "Text");
            return View(LoanInfo);
        }
        // GET: Loan/Create
        public ActionResult Create(long? UserId)
        {
            var loan = new sdtoLoanInfo();
            loan.RePaymentInterval = Data.Models.Enumerations.RepaymentInterval.Monthly;
            loan.Status = Data.Models.Enumerations.LoanStatus.Active;

            bfReport objReport = new bfReport(db);

            var bankInterest = db.GeneralSettings.FirstOrDefault().BankInterest;
            loan.InteresRate = Convert.ToSingle(bankInterest == null ? 0 : bankInterest.Value);

            var listUsers = db.User.Where(x => x.UserType == UserType.Member && x.IsDeleted == false && (UserId == null || UserId.Value == 0 || x.UserID == UserId));

            if (listUsers == null || listUsers.Count(x => x.UserID > 0) == 0)
            {
                SetDisplayMessage("Please create a loan member first");
                return RedirectToAction("Create", "Member");
            }

            loan.LoanCode = objReport.GenerateCode("LoanInfo");

            var userList = listUsers.OrderBy(x => x.FirstName).ToList();
            var users = userList.Select(x => new SelectListItem() { Value = x.UserID.ToString(), Text = x.FirstName + " " + x.LastName }).ToList();
            users.Insert(0, new SelectListItem() { Value = "0", Text = "Select a Member" });
            ViewBag.UserList = new SelectList(users, "Value", "Text");
            return View(loan);
        }
        public bool PostLoanIssue(sdtoLoanInfo LoanInfo)
        {
            bool tranFlag = true;

            //      var member = AppDb.User.Join(AppDb.AccountHeads, // the source table of the inner join
            //post => post.AccountHead.AccountHeadId,        // Select the primary key (the first part of the "on" clause in an sql "join" statement)
            //meta => meta.AccountHeadId,   // Select the foreign key (the second part of the "on" clause)
            //(post, meta) => new { Post = post, Meta = meta }).Where(x => x.Post.UserID == LoanInfo.UserId).Select(x => new { x.Post.UserID, AccountHead = new { AccountHeadId = x.Meta.AccountHeadId, AccountCode = x.Meta.AccountCode, AccountName = x.Meta.AccountName, AccountType = x.Meta.AccountType, AccountTypeId = x.Meta.AccountTypeId } }).FirstOrDefault();

            //from f in AppDb.User
            //join b in AppDb.AccountHeads on f.AccountHeadId equals b.AccountHeadId
            //where f.UserID == LoanInfo.UserId
            //select new { f.UserID, AccountHead = new sdtoAccountHead() { AccountHeadId = b.AccountHeadId, AccountCode = b.AccountCode, AccountName = b.AccountName, AccountType = b.AccountType, AccountTypeId = b.AccountTypeId } };

            //var member = members.FirstOrDefault();

            var member = AppDb.User.Where(x => x.UserID == LoanInfo.UserId).FirstOrDefault();

            //var member = AppDb.User.Include(x => x.AccountHeadId).Where(x => x.UserID == LoanInfo.UserId).FirstOrDefault();
            if (member != null)
            {
                var accHeadMember = AppDb.AccountHeads.Find(member.AccountHeadId);
                if (accHeadMember != null)
                {
                    var settingCashBookId = AppDb.GeneralSettings.FirstOrDefault().CashBookId;
                    //Post for Bank book
                    var accCashBook = AppDb.AccountBooks.Where(x => x.AccountBookId == settingCashBookId).FirstOrDefault();
                    if (accCashBook != null)
                    {
                        var receipt = new sdtoReceiptHeader()
                        {
                            BookId = accCashBook.AccountBookId,
                            TransDate = LoanInfo.TransactionDate.Value,
                            VoucherTotal = LoanInfo.LoanAmount, //Doubt: Voucher total should be loan amount or loan amount + additional value from user
                            TransType = ReceiptType.Receipt,
                            FinancialYearId = CurrentUser.UserSession.FinancialYearId.Value,
                            FromModule = 1,  //Doubt: 0 for "From Accounts", 1 for "From Posting"
                            Transaction = TransactionType.LoanEntry, //Doubt: //0 for Cash Receipt, 1 for Cash Payment, 2 for "Loan Entry", 3 for "Loan repayment"
                            TransId = LoanInfo.LoanId, //Doubt: Is transaction id loan id?
                            Cancelled = 0
                        };
                        AppDb.ReceiptHeader.Add(receipt);
                        AppDb.SaveChanges();

                        receipt.VoucherNo = accCashBook.ReceiptVoucherPrefix + receipt.Id + accCashBook.ReceiptVoucherSuffix;
                        AppDb.Entry(receipt).State = EntityState.Modified;
                        AppDb.SaveChanges();

                        // Member
                        var receiptDetailsDb = new sdtoReceiptDetails()
                        {
                            ReceiptsId = receipt.Id,
                            AccountId = accHeadMember.AccountHeadId,
                            Narration = "Loan issued",
                            Amount = LoanInfo.LoanAmount,
                            Display = 1
                        };

                        UpdateClosingBalance(accHeadMember.AccountHeadId, CurrentUser.UserSession.FinancialYearId.Value, LoanInfo.LoanAmount);
                        UpdateDayBookBalance(accHeadMember.AccountHeadId, CurrentUser.UserSession.FinancialYearId.Value, LoanInfo.TransactionDate.Value, LoanInfo.LoanAmount, TransactionType.LoanEntry);

                        // Cash Account
                        var receiptDetailsCr = new sdtoReceiptDetails()
                        {
                            ReceiptsId = receipt.Id,
                            AccountId = accCashBook.AccountHeadId.Value,
                            Narration = "Loan issued",
                            Amount = -1 * LoanInfo.LoanAmount,
                            Display = 1
                        };

                        UpdateClosingBalance(accCashBook.AccountHeadId.Value, CurrentUser.UserSession.FinancialYearId.Value, LoanInfo.LoanAmount);
                        UpdateDayBookBalance(accCashBook.AccountHeadId.Value, CurrentUser.UserSession.FinancialYearId.Value, LoanInfo.TransactionDate.Value, LoanInfo.LoanAmount, TransactionType.LoanEntry);

                        AppDb.ReceiptDetails.Add(receiptDetailsCr);
                        AppDb.ReceiptDetails.Add(receiptDetailsDb);
                        AppDb.SaveChanges();
                    }
                }
            }

            return tranFlag;
        }
        public bool CancelPostedLoanIssue(sdtoLoanInfo LoanInfo)
        {
            bool bFlag = true;
            var member = AppDb.User.Where(x => x.UserID == LoanInfo.UserId).FirstOrDefault();
            if (member != null)
            {
                var accHeadMember = AppDb.AccountHeads.Find(member.AccountHeadId);
                if (accHeadMember != null)
                {
                    var settingCashBookId = AppDb.GeneralSettings.FirstOrDefault().CashBookId;
                    //Post for Bank book
                    var accCashBook = AppDb.AccountBooks.Where(x => x.AccountBookId == settingCashBookId).FirstOrDefault();
                    if (accCashBook != null)
                    {
                        var header = AppDb.ReceiptHeader.Where(x => x.IsDeleted == false && x.Cancelled == 0 && x.BookId == accCashBook.AccountBookId && x.TransId == LoanInfo.LoanId && x.Transaction == TransactionType.LoanEntry).FirstOrDefault();
                        if (header != null)
                        {
                            header.Cancelled = 1;
                            AppDb.Entry(header).State = EntityState.Modified;
                            AppDb.SaveChanges();

                            var dtls = AppDb.ReceiptDetails.Where(x => x.ReceiptsId == header.Id && x.IsDeleted == false).ToList();
                            //dtls.ForEach(x => x.IsDeleted = true);

                            foreach (var dtlItem in dtls)
                            {
                                dtlItem.IsDeleted = true;
                                AppDb.Entry(dtlItem).State = EntityState.Modified;
                            }

                            AppDb.SaveChanges();
                        }
                    }
                }
            }
            return bFlag;
        }
 public ActionResult LoanRecall(sdtoLoanInfo objLoanInfo)
 {
     if (ModelState.IsValid)
     {
         sdtoLoanInfo sdtoloanInfo = db.sdtoLoanInfoes.Find(objLoanInfo.LoanId);
         sdtoloanInfo.Status = LoanStatus.Recalled;
         sdtoloanInfo.Notes = objLoanInfo.Notes;
         db.Entry(sdtoloanInfo).State = EntityState.Modified;
         db.SaveChanges();
         return RedirectToAction("Index");
     }
     return RedirectToAction("Index");
 }